Метод isTokenExpired возвращает true и false

Я новичок в angular, и я пытаюсь проверить свой токен аутентификации с помощью angular-jwt на Angular 6. Целью проверки токена будет разрешить разные кнопки, когда пользователь входит в систему, и показывать другой набор кнопок, когда они выходят из системы.

Это моя служба авторизации.

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

Теперь моя проблема заключается в том, что до того, как я войду в систему, он правильно регистрируется в консоли как истина, но после того, как я войду в систему и перейду на страницу профиля, кнопки не изменятся, потому что он все еще регистрирует истину, а затем снова регистрирует ложь.

Перед входом в систему: Перед входом в систему

После входа в систему: После входа в систему

Я думаю, это связано с использованием функции получения токена в модуле приложения, но я не уверен, как еще ее реализовать.

Компонент модуля моего приложения:

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

providers: [AuthService,JwtHelperService]
})

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

person Randika Peiris    schedule 30.05.2018    source источник


Ответы (2)


Лучше поздно, чем никогда, я только что столкнулся с этим вопросом. Это отличная статья о том, как реализовать пользовательские директивы в angular.

Отображение компонента на основе роли

очень полезно. Глядя на описание, это, на мой взгляд, то, что следует использовать

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

и теперь мы можем использовать такие директивы

<app-normal-users-can-view *appHasRole="'user'">
</app-normal-users-can-view>
person Community    schedule 10.06.2019
comment
Пожалуйста, вставьте соответствующую информацию в свой пост. Ссылки не вечны. См.: meta.stackexchange.com/a/8259/514519. - person Benjamin Urquhart; 11.06.2019
comment
Хорошо, у меня наконец-то появилась возможность редактировать и добавлять содержимое страницы внутри ответа. Спасибо за совет. - person ; 14.06.2019

Я также в настоящее время новичок в Angular Js Framework и начал учиться на более старых версиях. Итак, мое исправление для этого кода заключалось в том, что я вызвал внешнюю функцию с именем 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>
person dqureshiumar    schedule 20.02.2021