我一直在查看有关 [Angular 10] 使用基于用户角色的 AuthGuard 安全路由的博客,但没有我可以查看的示例演示或完整过程,任何人都可以帮助我实现 [Angular 10] Secure基于用户角色使用 AuthGuard 的路由与此博客相同或相似?这样我就可以把事情联系起来。谢谢。
我只是想在 angular 或 angular 10 中使用基于用户角色的 AuthGuard 完全实现安全路由。
我在后端有一个服务,或者我已经有包含用户角色的路由,端点包含角色,这是下面的示例 json。
如何将角色从 API 集成到守卫服务和路由?任何人都可以请启发我。谢谢。
示例数据:
{
"id": 2,
"emailAddress": "test@gmail.com",
"firstName": "Test",
"lastName": "Test Man",
"mobileNumber": "455555555",
"associatedAccount": "Sample",
"status": "Active",
"lastLogIn": null,
"invitedById": null,
"invitedByDate": null,
"identityId": "2",
"userAccountDto": [
{
"id": 2,
"accountId": 4,
"accountName": "Sample Company 1",
"displayName": "Sample Company",
"settings": "{\"propertySearchFilter\":[{\"type\":\"Region\",\"values\":null},{\"type\":\"State\",\"values\":[]},{\"type\":\"Repm\",\"values\":null}]}",
"userRoleDto": {
"id": 2,
"roleName": "Admin"
},
"accountDto": {
"accountId": 4,
"accountName": "Sample Company",
"displayName": "Sample Company",
"isActive": true,
"contactFirstName": null,
"contactLastName": null,
"contactPhone": null,
"contactEmailAddress": null,
"accountRoleDto": [
{
"id": 1,
"accountId": 4,
"roleName": "Admin"
},
{
"id": 5,
"accountId": 4,
"roleName": "Transaction Manager"
},
]
}
},
https://www.geekstrick.com/angular-10-secure-routes-using-authguard-based-on-user-role/
答案 0 :(得分:1)
Demo Guarding 用于保护路由。要首先使用守卫,您需要编写您的指南服务,如下所示。在下面的代码中认为您从 UserRolesService 获得角色 你会看到 canActivate 函数。该函数用于允许或不允许。在函数内部,您可以检查您的角色是否允许该角色返回 true 如果不返回 false
import { Injectable } from '@angular/core';
import { UserRolesService} from './user-roles.service';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RoleGuardService {
constructor(private getUserRoles: UserRolesService) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
return route.data.roles.some( ai => this.getUserRoles.getRoles().includes(ai) );
}
}
在你写了你的守卫而不是在 app.routing 中你需要使用 canActivate 属性来激活这个守卫到这条路线。
path: "admin",
component: AdminOnlyComponent,
canActivate: [RoleGuardService],
data: { roles: ['admin']
}