使用 Auth0 spa 快速入门时出错 [英] Error while using the Auth0 spa quickstart

查看:24
本文介绍了使用 Auth0 spa 快速入门时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个将使用 Auth0 进行用户身份验证的 Angular 2 网络应用.

我遵循了 Auth0 网站上的快速入门,但我'我收到错误 无法读取新 AuthService (auth.service.ts:9) 处未定义的属性 'WebAuth',即使 AuthService 已声明.

我错过了什么吗?非常感谢任何帮助.

这是我的代码

//app.component.ts

import { Component } from '@angular/core';从 '../../auth/auth.service' 导入 { AuthService };@成分({选择器:'应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {构造函数(公共身份验证:AuthService){auth.handleAuthentication();}}

//auth.service.ts

import { Injectable } from '@angular/core';从@angular/router"导入{路由器};导入 'rxjs/add/operator/filter';从'auth0-js'导入auth0;@Injectable()导出类 AuthService {auth0 = 新的 auth0.WebAuth({客户 ID: '*****',领域: '*****',responseType: 'token id_token',观众: '******',redirectUri: 'http://localhost:4200/callback',范围:'openid'});构造函数(公共路由器:路由器){}公共登录():无效{this.auth0.authorize();}公共句柄认证():无效{this.auth0.parseHash((err, authResult) => {如果(authResult && authResult.accessToken && authResult.idToken){window.location.hash = '';this.setSession(authResult);this.router.navigate(['/home']);}否则如果(错误){this.router.navigate(['/home']);控制台日志(错误);}});}私人 setSession(authResult): void {//设置访问令牌到期的时间const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());localStorage.setItem('access_token', authResult.accessToken);localStorage.setItem('id_token', authResult.idToken);localStorage.setItem('expires_at', expiresAt);}公共注销():无效{//从 localStorage 中删除令牌和过期时间localStorage.removeItem('access_token');localStorage.removeItem('id_token');localStorage.removeItem('expires_at');//返回home路径this.router.navigate(['/']);}公共 isAuthenticated(): 布尔 {//检查当前时间是否超过//访问令牌的到期时间const expiresAt = JSON.parse(localStorage.getItem('expires_at'));if (new Date().getTime() < expiresAt) {返回真;} 别的 {返回假;}}}

//app.html

</nav><主类=容器"><路由器插座></路由器插座></main>

谢谢

解决方案

你有没有试过这样导入:

import * as auth0 from 'auth0-js';

I'm currently working on an Angular 2 web app that will use Auth0 for user authentication.

I followed the quickstart at the Auth0 website, but I'm getting the error Cannot read property 'WebAuth' of undefined at new AuthService (auth.service.ts:9), even though AuthService is declared.

Am I missing something? Any help is very much appreciated.

This is my code

//app.component.ts

import { Component } from '@angular/core';
import { AuthService } from '../../auth/auth.service';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(public auth: AuthService) {
        auth.handleAuthentication();
    }
}

//auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import auth0 from 'auth0-js';

@Injectable()
export class AuthService {

    auth0 = new auth0.WebAuth({
        clientID: '*****',
        domain: '*****',
        responseType: 'token id_token',
        audience: '******',
        redirectUri: 'http://localhost:4200/callback',
        scope: 'openid'
    });

    constructor(public router: Router) { }

    public login(): void {
        this.auth0.authorize();
    }

    public handleAuthentication(): void {
        this.auth0.parseHash((err, authResult) => {
            if (authResult && authResult.accessToken && authResult.idToken) {
                window.location.hash = '';
                this.setSession(authResult);
                this.router.navigate(['/home']);
            } else if (err) {
                this.router.navigate(['/home']);
                console.log(err);
            }
        });
    }

    private setSession(authResult): void {
        // Set the time that the access token will expire at
        const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
        localStorage.setItem('access_token', authResult.accessToken);
        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('expires_at', expiresAt);
    }

    public logout(): void {
        // Remove tokens and expiry time from localStorage
        localStorage.removeItem('access_token');
        localStorage.removeItem('id_token');
        localStorage.removeItem('expires_at');
        // Go back to the home route
        this.router.navigate(['/']);
    }

    public isAuthenticated(): boolean {
        // Check whether the current time is past the
        // access token's expiry time
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        if (new Date().getTime() &lt; expiresAt) {
            return true;
        } else {
            return false;
        }
    }

}

//app.html

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header" *ngIf="auth" >
            <a class="navbar-brand" href="#">Auth0 - Angular</a>

            <button class="btn btn-primary btn-margin"
                    routerLink="/">
                Home
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="!auth.isAuthenticated()"
                    (click)="auth.login()">
                Log In
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="auth.isAuthenticated()"
                    (click)="auth.logout()">
                Log Out
            </button>

        </div>
    </div>
</nav>

<main class="container">
    <router-outlet></router-outlet>
</main>

Thank you

解决方案

Have you tried to import it this way:

import * as auth0 from 'auth0-js';

这篇关于使用 Auth0 spa 快速入门时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆