【问题标题】:Wait until a subscribe is called in angular等到 subscribe 以 Angular 调用
【发布时间】:2020-11-16 20:03:17
【问题描述】:

早上好, 我创建了一个 angualr 应用程序,我需要检查用户在路由中的角色。 我使用 canLoad 方法创建了一个服务“RoleGuardService”,该方法读取 JWS 令牌并检查用户权限:

import * as JWT from 'jwt-decode';
...
   const tokenPayload: App = JWT(token);
   if(tokenPayload.UserType == expectedRole){
      return true;
   }
   return false;

到目前为止一切顺利,但这迫使我声明硬编码的权限:

{ path: 'xxx', component: yyy, canLoad: [RoleGuardService], data: { expectedRole: 'Admin' } },

是否可以创建需要直接从 Web API 授权的方法? 喜欢:

    var isAllowed = false;
    this.http.get('https://xxx/check_user/').subscribe(result: bool) => {
        isAllowed = result;
    }
    ///wait until the subscribe is called
    return isAllowed;

【问题讨论】:

    标签: angular authentication jwt angular-router-guards


    【解决方案1】:

    你可以让 canLoad 返回布尔类型的 Observable (Observable<boolean>) 并返回类似 -

    return this.http.get('https://xxx/check_user/').map(result => result);
    

    【讨论】:

      【解决方案2】:

      您可以在 Core angular 中为 route 使用 canActivate 参数,该参数是为该类型的用例 https://angular.io/api/router/CanActivate

      创建的

      示例:

        {
          path: 'protectedRoute',
          component: SecureComponent,
          data: {
            authorities: ['ROLE_ADMIN'],
          },
          canActivate: [UserRouteAccessService]
        }
      
      
      
      
      
      @Injectable({ providedIn: 'root' })
      export class UserRouteAccessService implements CanActivate {
        constructor(
          private router: Router,
          private accountService: AccountService,
        ) {}
      
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
          const authorities = route.data['authorities'];
          return this.accountService.identity().pipe(
            map(account => {
              if (!account) {
                return false;
              }
      
              if (!authorities || authorities.length === 0) {
                return true;
              }
      
              const hasAnyAuthority =   authorities.some((authority: string) => account.authorities.includes(authority));
              if (hasAnyAuthority) {
                return true;
              }
              this.router.navigate(['accessdenied']);
              return false;
            })
          );
        }
      
      }
      

      其中 AccountService 是您获取当前登录用户的服务

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多