简体   繁体   English

isTokenExpired 方法返回 true 和 false

[英]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.我对 angular 很陌生,我正在尝试通过在 Angular 6 上使用 angular-jwt 来验证我的身份验证令牌。他们退出。

This is my authService.这是我的 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这是我的 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.....

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.我认为这是由于在 app 模块中使用了令牌 getter 函数,但我不确定如何实现它。

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.这是一篇关于如何在 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.我目前也是 Angular Js 框架的新手,并开始通过旧版本学习。 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 .所以我对此代码的修复是我调用名为loadToken()外部函数,它加载了我的Auth Token如果找到它,那么我的函数返回false否则返回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:进一步在 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 布尔值设置为false; 如果不带==的if语句返回true - boolean set to false; returns true on if statement without == 如果我们有效的令牌,Angular6 auth0 / angular2-jwt isTokenExpired函数始终返回false - Angular6 auth0/angular2-jwt isTokenExpired function always return false if we valid Token 为什么复选框事件状态返回字符串“ on”而不是true / false? - Why checkbox event status returns string “on” instead of true/false? HttpClient post返回true,但组件订阅function为false - HttpClient post returns true, but component subscribe function is false Angular 材料列表选项返回真,即使假 - Angular Material List Option returns true, even if false 在布尔TypeScript / JavaScript方法中返回true / false的正确方法? - Right way to return true/false in boolean TypeScript/JavaScript method? 我们可以使用复选框的 [checked] 属性的方法将其设置为 true/false - Can we use a method on [checked] property of checkbox to set it to true/false oidcSecurityService checkAuth 方法在使用 Identity Server 进行身份验证时返回 false - oidcSecurityService checkAuth method returns false when authenticated with Identity Server 如果key为true,则返回false的true - Return true of false if key is true AuthGuard 可以激活到函数结束并返回 false 而不是等待订阅返回 true - AuthGuard can activate goes to end of function and returns false instead of waiting for subscription to return true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM