Angular应用程序的角色和权限工具

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

我们正在构建角度应用程序,在其中调用后端REST API进行用户身份验证。该REST API使用Windows身份验证进行用户身份验证。

现在,我们想为我们的角度应用程序实现“角色和权限”。我们的要求如下

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

有人可以建议我们如何实现这一目标吗?

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

关于Vipul

angular authorization
2个回答
0
投票

Angular有一个称为guards的内置机制来实现这一目标-我们正在使用该机制来检查Keycloak服务器的用户权限。例如,有一个CanActivate保护器,您可以查看文档here

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

0
投票

[据我所知,您只需要在用户有权编辑页面的情况下才显示一个按钮。

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

我认为您需要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>
© www.soinside.com 2019 - 2024. All rights reserved.