0

我是 Angular 的新手,我正在尝试通过在 Angular 6 上使用 angular-jwt 来验证我的身份验证令牌。验证令牌的目的是在用户登录时允许使用不同的按钮,并在用户登录时显示不同的按钮集他们注销。

这是我的身份验证服务。

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

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

登录前:登录前

登录后: 登录后

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

我的应用模块组件:

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

providers: [AuthService,JwtHelperService]
})

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

2 回答 2

0

迟到总比没有好,我刚刚遇到这个问题。这是一篇关于如何在 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>
于 2019-06-10T23:25:13.720 回答
0

我目前也是 Angular Js 框架的新手,并开始通过旧版本学习。所以我对这段代码的修复是我调用了名为的外部函数loadToken(),它加载了我的Auth Token If it was found 所以我的函数返回falseelse 它返回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>
于 2021-02-20T10:47:06.647 回答