Angular - 是否可以对路由器防护的结果进行反转?

问题描述 投票:0回答:1

我正在编写一个使用 Okta 进行身份验证的 Angular 应用程序。我有一些页面,我只想允许用户在 not 身份验证时激活。我在我正在使用的 Okta 包版本中找不到任何防护或功能,但它确实有一个路由器防护 (OktaAuthGuard) 来检查用户是否经过身份验证is。是否可以使用这个守卫的相反结果,或者创建一个采用 OktaAuthGuard 的 canActivate() 函数的反函数的守卫,以获得我想要的功能?

封装版本:

@okta/okta-angular: 2.2.1

@okta/okta-signin-widget:5.16.1

angular angular-router okta angular-router-guards okta-signin-widget
1个回答
0
投票

这是不可能的,因为路由器守卫在从守卫的 CanActivate() 函数返回

true
false
值之前可能会或可能不会运行其他条件代码。对于您提到的包,Okta 路由器守卫将在返回 false 之前重定向到登录小部件页面(或启动替代登录流程)。

此问题的解决方案需要了解该路由守卫使用的逻辑。必须实现使用原始逻辑的逆向逻辑(即返回 true 而不是 false,反之亦然)的新路由守卫。

题中守卫的情况,查看源码[1]发现在CanActivate函数中使用了如下逻辑:

// Track states for current route
this.state = state;
this.onAuthRequired = route.data && route.data.onAuthRequired || this.onAuthRequired;

// Protect the route after accessing
this.oktaAuth.authStateManager.subscribe(this.updateAuthStateListener);
const isAuthenticated = await this.oktaAuth.isAuthenticated();
if (isAuthenticated) {
  return true;
}

await this.handleLogin(state.url);

return false;

此代码使用一个函数来检查用户是否已通过身份验证,从而能够激活受保护的路由。反转此逻辑的示例路由守卫看起来像下面的代码片段。您可以根据需要为这两种情况添加自己的重定向或其他处理方式:

import ...

export class NotAuthenticatedGuard implements CanActivate {

  authProvider:

  constructor(private router: Router,
              private oktaAuthService: OktaAuthService,
              private route: ActivatedRoute)
  {

    this.authProvider = oktaAuth;

  }

  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Promise<boolean>
  {

    if (await this.authProvider.isAuthenticated())
    {

      // Add handling here
      return false;

    }

    // Add handling here
    return true;

  }
}

来源: [1]:https://github.com/okta/okta-angular/blob/master/lib/src/okta/okta.guard.ts

© www.soinside.com 2019 - 2024. All rights reserved.