简体   繁体   中英

isTokenExpired method returns true and false

I'm quite new at angular and I'm trying to verify my authentication token by using angular-jwt on Angular 6.The purpose of verifying the token would be to allow different buttons when the user logs and show a different set of buttons when they log out.

This is my authService.

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

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

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

And this is bit of my HTML code

<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.....

Now my problem is before I login it logs on the console correctly as true, but after I login and go to the profile page the buttons won't change cause it still logs true and then logs false again.

Before logging in: 登录前

After logging in: 登录后

I think it's due to using the token getter function in the app module but I'm not sure how else to implement it.

My app module component:

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

providers: [AuthService,JwtHelperService]
})

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

Better late than never, I have just come across this question. This is a great article on how to implement custom directives in angular.

Display a component based on a role

extremely useful. Looking at the description, this is, in my opinion, what should be used

@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();
  }
}

and now we can use the directives like so

<app-normal-users-can-view *appHasRole="'user'">
</app-normal-users-can-view>

I am also currently new to Angular Js Framework and started learning via older versions. So my fix for this code was I called external function named loadToken() which loaded my Auth Token If it was found so my function returned false else it returned true .

Below is the code I have tried:

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);
    }
}

Further in the HTML code:

<!-- 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM