【问题标题】:Roles and Permission Tools for Angular ApplicationsAngular 应用程序的角色和权限工具
【发布时间】:2020-01-08 19:05:57
【问题描述】:

我们正在构建 Angular 应用程序,并在其中调用后端 REST API 进行用户身份验证。此 REST API 使用 windows 身份验证进行用户身份验证。

现在,我们想为我们的 Angular 应用实现角色和权限。 我们的要求如下

  1. 具有只读访问权限的用户应该只能阅读我们应用中的某些页面。
  2. 应允许具有写入权限的用户修改特定页面中的数据。

谁能建议我们如何实现这一目标?

可能正在使用一些开源工具?

问候 维普尔

【问题讨论】:

  • 你能提供一些代码吗?你已经做了什么?

标签: angular authorization


【解决方案1】:

Angular 有一个名为guards 的内置机制来实现这一点——我们使用它来检查来自 Keycloak 服务器的用户权限。比如有一个CanActivateguard,可以看文档here

const adminRoutes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: 'crises', component: ManageCrisesComponent },
          { path: 'heroes', component: ManageHeroesComponent },
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  }
];

【讨论】:

    【解决方案2】:

    如果我理解正确,您需要的是仅当用户有权编辑页面时才显示一个按钮。

    如果您想阻止某种用户访问页面,Guard 很有用。根据您的帖子,所有用户都可以访问该页面。但是,并非所有人都可以编辑该页面。

    我想你需要一个resolver,直接从路由发送用户数据。

    这就是它的工作原理:

    @Injectable({ providedIn: 'root' })
    
    export class MeResolver implements Resolve<any> {
      constructor(private http: HttpClient) {}
    
      resolve(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<any>|Promise<any>|any {
        // This should return user data (take care of sending token too)
        return this.http.get<any>(`${environment.api}/auth`)
      }
    }
    

    在您的路由文件中,您必须正确:

    {
        path: '',
        component: UserComponent,
        resolve: [ MeResolver ],
    }
    

    然后,在您的组件中,您可以使用 route 属性访问解析器,例如:

    export class UserComponent {
    
      $me: Observable<any> = this.route.data.pipe(map(elem => elem[0]));
    
      constructor(private route: ActivatedRoute) { }
    
    }
    

    这样,您可以在 HTML 中隐藏“编辑”按钮:

    <button (click)="edit()" *ngIf="(me$ | async)?.role.admin">EDIT</button>
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2023-04-03
      • 1970-01-01
      • 2017-02-06
      • 2010-12-12
      • 2011-07-28
      • 1970-01-01
      • 2012-02-04
      • 2014-08-19
      相关资源
      最近更新 更多