isTokenExpired方法返回true和false

时间:2018-05-30 16:00:24

标签: angular jwt angular2-services angular2-jwt

我在角度很新,我试图通过在Angular 6上使用angular-jwt来验证我的身份验证令牌。验证令牌的目的是在用户登录时显示不同的按钮并显示不同的设置他们退出时按钮。

这是我的authService。

import { JwtHelperService } from '@auth0/angular-jwt';

constructor(private http:HttpClient, public jwtHelper:JwtHelperService)
{}

loggedIn()
{
  console.log(this.jwtHelper.isTokenExpired(this.authtoken));
}

这是我的HTML代码

<a *ngIf="!authService.loggedIn()" [routerLink]="['/login']"><button class.....
<a *ngIf="!authService.loggedIn()" [routerLink]="['/register']"><button class.....   
<a *ngIf="authService.loggedIn()" [routerLink]="['/profile']"><button class....
<a *ngIf="authService.loggedIn()" [routerLink]="['/profile']"><button class.....

现在我的问题是在我登录之前正确登录控制台正确,但是在我登录并转到配置文件页面后,按钮不会改变,因为它仍然记录为真,然后再次记录为假。

登录前:Before Logging in

登录后: After logging in

我认为这是因为在app模块中使用了令牌getter函数,但我不确定如何实现它。

我的app模块组件:

....
imports: [BrowserModule,
[JwtModule.forRoot({
config: {tokenGetter:tokenGetter,whitelistedDomains['localhost:3000']}
})]

providers: [AuthService,JwtHelperService]
})

export function tokenGetter() {
return localStorage.getItem('access_token');
}

2 个答案:

答案 0 :(得分:0)

迟到总比没有好,我刚遇到这个问题。这是一篇很棒的文章,介绍了如何在angular中实现自定义指令。

Display a component based on a role

极其有用。通过查看说明,我认为这是应该使用的

.as-console-wrapper { max-height: 100% !important; top: auto; }

现在我们可以使用类似的指令

@Directive({
  selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit, OnDestroy {
  // the role the user must have 
  @Input() appHasRole: string;

  stop$ = new Subject();

  isVisible = false;

  /**
   * @param {ViewContainerRef} viewContainerRef 
   *    -- the location where we need to render the templateRef
   * @param {TemplateRef<any>} templateRef 
   *   -- the templateRef to be potentially rendered
   * @param {RolesService} rolesService 
   *   -- will give us access to the roles a user has
   */
  constructor(
    private viewContainerRef: ViewContainerRef,
    private templateRef: TemplateRef<any>,
    private rolesService: RolesService
  ) {}

  ngOnInit() {
    //  We subscribe to the roles$ to know the roles the user has
    this.rolesService.roles$.pipe(
        takeUntil(this.stop$)
    ).subscribe(roles => {
      // If he doesn't have any roles, we clear the viewContainerRef
      if (!roles) {
        this.viewContainerRef.clear();
      }
      // If the user has the role needed to 
      // render this component we can add it
      if (roles.includes(this.appHasRole)) {
        // If it is already visible (which can happen if
        // his roles changed) we do not need to add it a second time
        if (!this.isVisible) {
          // We update the `isVisible` property and add the 
          // templateRef to the view using the 
          // 'createEmbeddedView' method of the viewContainerRef
          this.isVisible = true;
          this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
      } else {
        // If the user does not have the role, 
        // we update the `isVisible` property and clear
        // the contents of the viewContainerRef
        this.isVisible = false;
        this.viewContainerRef.clear();
      }
    });
  }

  // Clear the subscription on destroy
  ngOnDestroy() {
    this.stop$.next();
  }
}

答案 1 :(得分:0)

我目前也是 Angular Js 框架的新手,并开始通过旧版本学习。所以我对这段代码的修复是我调用了名为 loadToken() 的外部函数,它加载了我的 Auth Token 如果找到了,我的函数返回 false 否则返回 true

下面是我试过的代码:

import { JwtHelperService  } from '@auth0/angular-jwt';
//Some More Code might be different for you, so pasting only the required code
export class AuthService {
    authToken : any;
    constructor(private http: HttpClient, private jwtHelper: JwtHelperService) { }
    loadToken(){
        const token = localStorage.getItem('id_token');
        this.authToken = token;
        return this.authToken;
    }
    // Check if the token is Valid
    loggedIn(){
        this.authToken = this.loadToken();
        console.log(this.jwtHelper.isTokenExpired(this.authToken));
        return this.jwtHelper.isTokenExpired(this.authToken);
    }
}

进一步在 HTML 代码中:

<!-- If returned False this will be displayed -->
<li *ngIf = "!authService.loggedIn()" class="nav-item" [routerLinkActive] = "['active']" [routerLinkActiveOptions] = "{ exact: true}">
    <a class="nav-link" [routerLink] = "['/profile']">Profile</a>
</li>
<!-- If returned True this will be displayed -->
<li *ngIf="authService.loggedIn()" class="nav-item" [routerLinkActive] = "['active']" [routerLinkActiveOptions] = "{ exact: true}">
    <a class="nav-link" [routerLink] = "['/register']">Register</a>
</li>
<li *ngIf="authService.loggedIn()" class="nav-item" [routerLinkActive] = "['active']" [routerLinkActiveOptions] = "{ exact: true}">
    <a class="nav-link" [routerLink] = "['/login']">Login</a>
</li>
相关问题