【问题标题】:Routing and Authorization in Angular 7Angular 7 中的路由和授权
【发布时间】:2019-12-07 18:01:44
【问题描述】:

我尝试在 Angular 7 中使用路由实现标准 JWT 授权。我的 app-routing.module.ts 的一部分:

{
    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 组件中,我有带有“登录”项的下拉列表,我的代码有:

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(['']) 不起作用。而不是 '' url 浏览器打开 this.router.navigate(['401']); 因为 helper.isTokenExpired(myRawToken) 无法刷新令牌。但是,如果我在浏览器中按 F5(刷新)并转到 localhost:4200/ - 我的页面将打开。

我做错了什么?

如何刷新令牌?

【问题讨论】:

    标签: angular routing jwt


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这个对我有用!我在auth service refreshyoken()中写了一个新方法:myRawToken = localStorage.getItem('token'); isExpired = helper.isTokenExpired(myRawToken);之后效果很好!
    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多