当我使用Auth0凭据登录并转到个人资料页面时,出现以下错误:
访问令牌必须存在才能获取配置文件
登录URL时可以看到访问令牌,但是不能保存。希望有人可以提供帮助。 Auth0网站上的以下教程仅停留在此。任何想法都很棒。如果需要,请随时询问更多信息。
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import * as auth0 from 'auth0-js';
@Injectable()
export class AuthService {
private _idToken: string;
private _accessToken: string;
private expiresAt: number;
auth0 = new auth0.WebAuth({
clientID: 'my id,
domain: 'my domain',
responseType: 'token id_token',
redirectUri: 'http://localhost:',
scope: 'openid profile'
});
map: any;
userProfile: any;
constructor(public router: Router) {
this._idToken = '';
this._accessToken = '';
this.expiresAt = 0;
}
public login(): void {
sessionStorage.url = window.location.href;
this.auth0.authorize();
}
get accessToken(): string {
return this._accessToken;
}
get idToken(): string {
return this._idToken;
}
public getProfile(cb): void {
if (!this._accessToken) {
throw new Error('Access Token must exist to fetch profile');
}
const self = this;
this.auth0.client.userInfo(this._accessToken, (err, profile) => {
if (profile) {
self.userProfile = profile;
}
cb(err, profile);
});
}
public handleAuthentication(): void {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
this.setSession(authResult);
// this.router.navigate(['/']);
} else if (err) {
// this.router.navigate(['/']);
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'));
return new Date().getTime() < expiresAt;
}
public renewTokens(): void {
this.auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
} else if (err) {
alert(`Could not get a new token (${err.error}:
${err.error_description}).`);
this.logout();
}
});
}
}
答案 0 :(得分:0)
我不确定您遵循哪个教程,但是Auth0在其Angular Quickstart中的当前建议并未将访问令牌保存在LocalStorage中。只是出于安全原因将其保留在内存中。
您的getProfile
函数显然将在第一行失败,因为this._accessToken
从未设置为您在handleAuthentication
函数中收到的实际令牌。
您可以通过将以下行添加到setSession
函数中来解决此问题:
this._accessToken = authResult.accessToken;
我建议通过不将令牌存储在浏览器的本地存储中来进一步改善这一点,您可以遵循官方文档here中介绍的最佳做法。