【问题标题】:Angular JWT Token refresh [closed]Angular JWT令牌刷新[关闭]
【发布时间】:2020-08-25 12:23:24
【问题描述】:

我有这个带有 .Net Core 后端的 Angular 应用程序,使用 JWT 身份验证令牌。一切都运行良好,除了这一点:登录发生时,应该立即出现一个按钮(仅当本地存储中存在 JWT 时)......但它没有!只有当我刷新页面时,按钮才会出现在导航栏中!无论如何我可以解决这个问题吗?提前致谢!

这是我使用变量“isLoggedIn”的组件,因此按钮是否显示: top-bar.component.html

<mat-toolbar class="mat-elevation-z10 toolbar-style">
    <a [routerLink]="['/']">
        <img class="top-bar-logo" src="assets/Images/DocShareAppLogo.png" alt="DocShareApp-Automobile">
    </a>
    <span class="spacer"></span>
    <div class="spaceInButtons" *ngIf="isLoggedIn">
        <mat-menu #appAccountMenu="matMenu">
            <button routerLink="personalInfo" mat-menu-item>Personal Info</button>
        </mat-menu>

        <a mat-raised-button class="account-button-color" [matMenuTriggerFor]="appAccountMenu">
            My Account
        </a>
    </div>
    <mat-menu #appFabAccount="matMenu">
        <button routerLink="registerLogin" mat-menu-item>Register/Login</button>
    </mat-menu>
    <a mat-fab class="account-button-color" [matMenuTriggerFor]="appFabAccount">
        <mat-icon>account_circle</mat-icon>
    </a>
</mat-toolbar>

top-bar.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../shared/auth.service';


@Component({
  selector: 'app-top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.css']
})
export class TopBarComponent implements OnInit {

  isLoggedIn = false;

  constructor(private authService: AuthService) { }

  ngOnInit(): void {
    this.isLoggedIn = this.authService.isAuthenticated();
  }

}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormGroupDirective } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  readonly rootURL = 'https://localhost:5001/';

  constructor(private httpClient: HttpClient, private toastr: ToastrService, private router: Router) { }

  postLogin(formModel: FormGroup, formDirective: FormGroupDirective){
    return this.httpClient.post(this.rootURL + 'Users/login', formModel).subscribe(
      (response: any) => {
        if (response.succeeded)
        formModel.reset();
        formDirective.resetForm();
        localStorage.setItem('token', response.token);
        //localStorage.removeItem('token');
        this.router.navigateByUrl('/');
        this.toastr.success('You have been logged in', response.message, { positionClass: 'toast-top-right' } )
      },
      errorResponse => {
       this.toastr.error(errorResponse.error.message, 'Login unsuccessful', { positionClass: 'toast-top-right' });
        }
    );  
  }

  isAuthenticated(): boolean{
    if (localStorage.getItem('token')){
      return true;
    }
    else{
      return false;
    }
  }
}

【问题讨论】:

  • 请贴出容易出错的代码。
  • 我发布了服务类,如果您需要html或其他内容,请告诉我
  • 将代码发布为图像使其难以复制。一个更好的版本将是一个最小的工作示例(例如使用 Stackblitz)。是的,没有模板就不清楚了。
  • 您的isAuthenticated() 检查发生在postLogin() 检查之前吗?发布您的模板代码!
  • isAuthenticated() 被调用,因此检查令牌是否在本地存储(浏览器)中,如果是,则证明用户的 postLogin() 成功(因为服务器返回了一个jwt),所以会出现navbar上的按钮!

标签: angular .net-core jwt


【解决方案1】:

您可以在登录成功后使用对象通知您的组件更新模板

auth.service.ts

loginSubject = new BehaviorSubject<boolean>(false);

setLogin(status) {
  this.loginSubject.next(status);
}

然后在设置 this.toastr.success / this.toastr.error 后使用 setLogin(true)

top-bar.component.ts

ngOnInit(): void {
  this.authService.loginSubject.subscribe(
    status => this.isLoggedIn = status
  )
}

【讨论】:

  • 非常感谢您提供此解决方案!在对 BehaviorSubject 进行了一些研究之后,这很有意义!干杯!
  • 哈哈谢谢我也学了...
猜你喜欢
  • 2021-04-06
  • 2017-10-11
  • 2016-10-14
  • 2016-03-05
  • 2016-06-25
  • 2021-01-19
  • 1970-01-01
  • 2017-12-31
  • 2017-12-26
相关资源
最近更新 更多