有没有办法使用 lib angular-auth-oidc-client 轻松处理基于角色的授权?
一旦用户在网站上,我想识别他们,所以我使用auto-login-all-routes警卫,到目前为止一切对我来说都很好。但我只想在 userData 包含特定角色时才允许访问,否则重定向到未经授权的页面。
起初,我虽然可以创建一个自定义版本的 auto-login-all-routes.guard.ts,但由于使用的大多数服务都不是由模块导出的,所以这似乎不是一个好主意。
你有什么建议吗?
有没有办法使用 lib angular-auth-oidc-client 轻松处理基于角色的授权?
一旦用户在网站上,我想识别他们,所以我使用auto-login-all-routes警卫,到目前为止一切对我来说都很好。但我只想在 userData 包含特定角色时才允许访问,否则重定向到未经授权的页面。
起初,我虽然可以创建一个自定义版本的 auto-login-all-routes.guard.ts,但由于使用的大多数服务都不是由模块导出的,所以这似乎不是一个好主意。
你有什么建议吗?
使用2个后卫。
第一个进行身份验证:
auto-login-all-routes.guard
然后是一个自定义警卫来监听oidcSecurityService.userData$和检查角色。
这是我目前正在使用的一个示例,不确定它是否是您正在寻找的。
路线
{
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()
);
}
}