【问题标题】:Angular 7 CanActivate Guards Failing overAngular 7 CanActivate Guards 故障转移
【发布时间】:2018-11-27 16:28:58
【问题描述】:

我的所有路线上都有 CanActivate 守卫,它们正在故障转移。

例如,我有两个警卫:

export class AuthenticationGuard implements CanActivate {
    constructor(private as: AuthenticationService, private router: Router) { }

    canActivate() {
        if (this.as.isLoggedIn()) {
            return true;
        }

        this.router.navigate(['/login']);

        return false;
     }
    }

export class IsAdminGuard implements CanActivate {
    constructor(private us: UserService, private router: Router) { }

    canActivate() {
        if (this.us.isAdmin()) {
            return true;
        }

        this.router.navigate(['/home']);

        return false;
    }
}

还有我的路线守卫

const routes: Routes = [
    {
        path: 'home',
        component: DashboardComponent,
        canActivate: [AuthenticationGuard, IsAdminGuard]
    }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
});

发生的情况是,如果AuthenticationGuard 失败,它有时会检查IsAdminGuard,而不是在未通过身份验证时将某人路由到/login,而是将他们发送到/home将他们发送到不同的错误页面,因为他们没有经过身份验证并且不是管理员,并且守卫应该在第一次失败时将他们踢出。

如果我删除AuthenticationService 在调用isLoggedIn() 时检查的身份验证jwt,刷新/home 路由并可以跟踪AuthenticationGuard 返回false 和还在打电话给IsAdminGuard

这是isLoggedIn()的代码

isLoggedIn = () => {
    const token = this.get();
    const decoded = this.decode(token);

    return token && this.isNotExpired(decoded);
};  

decode = (token: string) => {
    const validToken = () => parts.length < 3
    const parts = token ? token.split('.') : '';

    if (!token || validToken()) {
        return '{}';
    }

    const payload = validToken() ? parts[1] : '{}';

    return JSON.parse(atob(payload));
};

private isNotExpired = (decodedToken) => this.getExpiryFrom(decodedToken) > new Date();

private getExpiryFrom = (decodedToken) => new Date(decodedToken.exp * 1000);

想法?

【问题讨论】:

  • 如果改变 CanActivate Array 中守卫的顺序会发生什么?
  • isLoggedIn() 是异步的吗?
  • @Phix 它是同步的 - 它只是检查身份验证令牌的到期时间
  • 你能把它贴在这里只是为了覆盖所有的基础
  • FWIW,在我的 authguards 中,我不做路由。我只是从我的 authservice 调用注销功能,因此路由被统一处理并清除任何异常。

标签: angular angular7 canactivate


【解决方案1】:

考虑让您的 isAdmin 防护短路,以重新检查身份验证状态。这样,身份验证的真实性将永远不会被您的 isAdmin 真实性结果所覆盖。它可能看起来多余,但它会起作用。

【讨论】:

  • 是的,我已经尝试过了,它确实有效——尽管我确实想让每个守卫都保持原子性——希望避免将它们耦合在一起并可能暴露一个潜在的问题
猜你喜欢
  • 2010-10-09
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 2012-07-13
  • 2014-06-14
相关资源
最近更新 更多