Angular 7 中的路由和授权

Routing and Authorization in Angular 7

我尝试在 Angular 7. app-routing.module.ts:

中使用路由实现标准 JWT 授权
{
    path: '',
    component: MainComponent,
    canActivate: [AuthGuard]
      },
  {
    path: '401',
    component: UnauthorizeComponent
  }

我也有auth.service.ts:

const helper = new JwtHelperService();
const myRawToken = localStorage.getItem('token');
const isExpired = helper.isTokenExpired(myRawToken);

@Injectable()
export class AuthService {

...

  public isAuthenticated(): boolean {
    return !isExpired;

还有 - auth-guard.service.ts:

@Injectable()
export class AuthGuardService  implements CanActivate {

...

  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['401']);
      return false;
    }
    return true;
  }
}

在 Header 组件中,我有 dropdown-list 和 "login" 项目,我的代码有:

sendLogin() {

    const body = new HttpParams()
      .set('username', this.loginForm.value.login)
      .set('password', this.loginForm.value.password);

    this.authService.login(body.toString())
      .pipe(
        catchError(err => {
          return ......;
        }))
      .pipe(
        tap(resp => {
          localStorage.setItem('token', resp.headers.get('Authorization'));
          this.router.navigate(['']);
        }))
      .subscribe();
  }

所以,它工作正常,但是 this.router.navigate(['']) 在我的 header 组件中不起作用。而不是 '' url 浏览器打开 this.router.navigate(['401']); 因为 helper.isTokenExpired(myRawToken) 无法刷新令牌。但是,如果我在浏览器中按 F5(刷新)并转到 localhost:4200/ - 我的页面打开。

我做错了什么?

如何刷新令牌?

如果您的令牌在 localStorage 中,任何服务都会在初始化时从那里获取它。因此,在授权期间,您在 localStorage 中放置了一个令牌,但是守卫引用的授权服务在其变量中保留了一个变量,该变量还没有来自 localStorage 的令牌。因此,使用 F5,您启动一​​个服务并且它已经看到它。需要扩展授权服务,让答案一来,token变量中的数据