angular - Angular 11 - 基于角色的身份验证不与其他角色一起使用(只有“操作员”在工作)
问题描述
只有 'operator' 可以访问该页面,当其他具有 'super_admin' 角色的帐户不能再访问该页面。我想限制某个角色的其他页面。
html:
<a mat-list-item
routerLink="/webinarcrud"
routerLinkActive="active"
*ngIf="dataService.roleMatch(['operator']) || dataService.roleMatch(['super_admin'])"
class="menuNav">
<mat-icon class="icon">computer</mat-icon>
Webinars
</a>
<a mat-list-item
routerLink="/organizationcrud"
routerLinkActive="active"
*ngIf="dataService.roleMatch(['super_admin'])"
class="menuNav">
<mat-icon class="icon">apartment</mat-icon>
Organizations
</a>
路由模块:
{
path: 'dashboard',
component: DashboardComponent,
canActivate:[AuthGuardGuard],
data:{ roles:['operator']} || {roles:['super_admin'] }
}
数据服务:
public roleMatch(allowedRoles): boolean {
let isMatch = false;
const userRoles: any = this.token.getRoles();
if (userRoles != null && userRoles) {
for (let i = 0; i < userRoles.length; i++) {
for (let j = 0; j < allowedRoles.length; j++) {
if (userRoles[i].name === allowedRoles[j]) {
isMatch = true;
return isMatch;
} else {
return isMatch;
}
}
}
}
}
令牌服务:
public getRoles(){
return JSON.parse(localStorage.getItem("roles"));
}
身份验证:
if (this.token.getToken() !== null) {
const role = route.data["roles"] as Array<string>;
const accessToken = route.data.accessToken as string;
if (role) {
const match = this.dataService.roleMatch(role);
if (match) {
return true;
} else {
this.router.navigate(["/login"]);
return false;
}
}
}
this.router.navigate(["/login"]);
return false;
}
解决方案
尝试以下更改 -
路由模块:
{path: 'dashboard', component: DashboardComponent, canActivate:[AuthGuardGuard], data:{roles:['operator','super_admin']}}
数据服务:
public roleMatch(allowedRoles) :boolean{
let isMatch = false;
const userRoles: any = this.token.getRoles();
if(userRoles) {
for(let i = 0; i<userRoles.length; i++) {
if(allowedRoles.indexOf(userRoles[i].name) !== -1){
isMatch = true;
break;
}
}
}
return isMatch;
}
推荐阅读
- c - 为什么这个变量在传递给函数时会改变
- depth-first-search - 这是 BFS 和 DFS 的正确顺序吗?
- caching - 如果页面先前已缓存,是否会看到新的缓存控制标头?
- php - 如何从会话中注销?
- directus - 检索由语言环境指定的文章列表(Directus 翻译)
- build - 如何在 _config.yml 中使用环境变量?
- elasticsearch - 具有多个类别的弹性搜索查询
- bash - 防止 tmux 的 pane_title 被更新
- git - 如何仅在最后一次提交时获取 git repo
- c# - DataGridView 在窗体 Windows 10 上不可见