【问题标题】:Authorization based on roles基于角色的授权
【发布时间】:2022-01-01 00:03:38
【问题描述】:

有没有办法通过 lib angular-auth-oidc-client 轻松处理基于角色的授权?

一旦用户在网站上,我想识别他们,所以我使用auto-login-all-routes 守卫,到目前为止一切对我来说都很好。但我只想在 userData 包含特定角色时才允许访问,否则重定向到未经授权的页面。

起初我虽然可以创建一个自定义版本的 auto-login-all-routes.guard.ts,但由于使用的大多数服务都不是由模块导出的,这似乎不是一个好主意.

你有什么建议吗?

【问题讨论】:

    标签: angular angular-router-guards angular-auth-oidc-client


    【解决方案1】:

    使用 2 个守卫。

    第一个验证:

    auto-login-all-routes.guard  
    

    然后是一个自定义守卫来监听oidcSecurityService.userData$ 并检查角色。

    【讨论】:

      【解决方案2】:

      这是我目前正在使用的一个示例,不确定它是否是您要查找的。​​p>

      路线

      {
        path: 'import',
        component: ImportComponent,
        canActivate: [AuthGuard, RoleGuard],
        data: { roles: new Set([UserRole.admin, UserRole.developer]) },
      },
      

      守卫

      @Injectable({
        providedIn: 'root',
      })
      export class RoleGuard implements CanActivate {
        constructor(private store: Store<AppState>, private location: Location) {}
      
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
          return this.store.select(selectUserRoles).pipe(
            debounce((roles) => (roles ? EMPTY : timer(2500))),
            map((roles) => {
              const permittedRoles = (route.data as RouteData).roles;
              if (
                roles &&
                Array.from(roles.values()).some((role) => permittedRoles.has(role))
              ) {
                return true;
              } else {
                alert(
                  `Requires one of the following roles: ${Array.from(permittedRoles)
                    .map((role) => getRoleName(role))
                    .join(', ')}`
                );
                this.location.back();
                return false;
              }
            }),
            first()
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-12-14
        • 2017-04-12
        • 2018-07-21
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        • 2013-10-21
        • 2016-12-10
        相关资源
        最近更新 更多