我正嘗試使用auth0從angular2應用程序進行身份驗證。貝婁是我的身份驗證服務(如資源,我用this和this和this):使用tokenNotExpired方法的auth0身份驗證問題
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
declare var Auth0Lock: any;
@Injectable()
export class AuthenticationService{
//Configure Auth0
lock = new Auth0Lock('my_client_id', 'my_domain', {});
//Store profile object in auth class
userProfile: Object;
constructor(){
this.lock.on("authenticated", (authResult)=>{
localStorage.setItem('id_token', authResult.idToken);
this.lock.getProfile(authResult.idToken, (error, profile) =>{
if(error){
console.log(error);
return;
}
localStorage.setItem('profile', JSON.stringify(profile));
this.userProfile = profile;
})
});
}
public login(){
console.log('Login');
this.lock.show();
}
public isAuthenticated(){
console.log(tokenNotExpired());
return tokenNotExpired();
}
public logout(){
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
this.userProfile = undefined;
}
}
,因爲我用的數據庫auth0身份提供商。我設法使用Auth0鎖對象(我正在接收令牌)登錄,但是當我想要隱藏/顯示某些按鈕時,即使在登錄後,tokenNotExpired()方法始終返回false。
<button md-button (click)="login()" *ngIf="!authService.isAuthenticated()">
<md-icon class="demo-toolbar-icon">input</md-icon>
Login
</button>
<button md-button (click)="logout()" *ngIf="authService.isAuthenticated()">
Logout
<md-icon class="demo-toolbar-icon">exit_to_app</md-icon>
</button>
爲什麼tokenNotExpired方法總是返回false以及如何解決此問題以便我可以隱藏/顯示元素?
編輯
我下面的代碼添加到認證服務:
import { tokenNotExpired, AuthHttp, AuthConfig } from 'angular2-jwt';
declare var Auth0Lock: any;
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'id_token',
tokenGetter: (() => localStorage.getItem('id_token'))
}), http, options);
}
@NgModule({
providers: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
]
})
@Injectable()
export class AuthenticationService{
//Configure Auth0
lock = new Auth0Lock('my_client_id', 'my_domain', {});
'tokenNotExpired'內部使用'tokenGetter'。你是如何配置它的?請參閱angular2-jwt。 – CSchulz
@CSchulz我不知道我必須配置'tokenGetter'。我遵循所發佈資源的示例。什麼配置適合我的情況? – florin