gpt4 book ai didi

javascript - 具有很少 Angular 色访问权限的 Angular JWT

转载 作者:行者123 更新时间:2023-12-01 15:34:29 24 4
gpt4 key购买 nike

我想使用多个 Angular 色来访问应用程序中的 View ,如果我使用一个 Angular 色一切正常,但是当我使用多个 Angular 色时, View 不授予访问权限

我的模型用户有这个:

export class User {
role: Role[]; // I change - role: Role[] for few roles
expiresIn: string;
aud: string;
iss: string;
token?: string;
}

export const enum Role {
Admin = 'admin',
User = 'user',
Engineer = 'engineer'
}

我的后端给我的 token 与 Angular 色:
//....
role: (2) ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
//....

如果我在登录方法中使用它
tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'][0]   - first element in array

我只有 1 个 Angular 色,代码工作正常,但我可以有许多属于不同 Angular 色的用户,如果至少有 1 个 Angular 色,我需要应用程序授予他们访问权限

我在授权服务中处理 token 解码和获取 Angular 色
signin(username:string, password:string ) {
return this.http.post<User>(`${environment.apiUrl}${environment.apiVersion}Profile/Login`, {username, password})
.pipe(map(user => {
if (user && user.token) {
let tokenInfo = this.getDecodedAccessToken(user.token); // decode token
this.session = {
token: user.token,
role: tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'], - add this [0]
expiresIn: tokenInfo.exp,
aud: tokenInfo.aud,
iss: tokenInfo.iss,
}
localStorage.setItem('currentUser', JSON.stringify(this.session));
this.currentUserSubject.next(this.session);
}
return this.session;
}))
}

例如 sigin 方法
Login() {
this.auth.signin(this.signinForm.value.email, this.signinForm.value.password)
.pipe(first())
.subscribe(
data => {
console.log("User is logged in");
this.router.navigate(['/dashboard']);
this.loading = false;
});
}

不确定我是否正确指定了多个访问 Angular 色
//......
const adminRoutes: Routes = [
{
path: 'dashboard',
loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGaurd],

},
{
path: 'books',
loadChildren: () => import('./views/books/books.module').then(m => m.BooksModule),
canActivate: [AuthGaurd],
data: { roles: [Role.Admin] } <- work fine if 1 role
},
{
path: 'person',
loadChildren: () => import('./views/person/person.module').then(m => m.PersonModule),
canActivate: [AuthGaurd],
data: { roles: [Role.Admin, Role.Engineer] } <- if have 1 role - admin - open
},
{
path: 'eqip',
loadChildren: () => import('./views/eqip/eqip.module').then(m => m.PersonModule),
canActivate: [AuthGaurd],
data: { roles: [Role.Engineer] } <- not open becouse only admin role
}];

const routes: Routes = [
{
path: '',
redirectTo: 'applayout-sidebar-compact/dashboard/v1',
pathMatch: 'full',
},
...
{
path: '**',
redirectTo: 'others/404'
}];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
//......

和 guard 服务
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
const currentUser = this.auth.currentUserValue;
// in auth.service.ts
// constructor(private http: HttpClient) {
// this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
// this.currentUser = this.currentUserSubject.asObservable();

// }
// public get currentUserValue(): User {
// return this.currentUserSubject.value;
// }
if (this.auth.isUserLoggedIn()) {


// test code
const ter = route.data.roles.includes(currentUser.role) <- Error now here
console.log(ter)



// main check role code
// if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
// this.router.navigate(["/"]);
// return false;
// }

return true;

}
this.auth.setRedirectUrl(url);
this.router.navigate([this.auth.getLoginUrl()]);
return false;

}

localStorage 中的 token :
aud: "Service"
expiresIn: 1591967261
iss: "USs"
role: ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHR....

更改 app-routing.module.ts
@NgModule({
imports: [RouterModule.forRoot(routes, {
useHash: true,
initialNavigation: 'enabled',
paramsInheritanceStrategy: 'always',
relativeLinkResolution: 'corrected',
scrollPositionRestoration: 'enabled',
})],
exports: [RouterModule]

错误
Uncaught (in promise): TypeError: Cannot read property 'includes' of undefined

TypeError:无法读取未定义的属性“包含”

最佳答案

也可能是 typescript 枚举不是字符串。
所以比较 enum用字符串永远不会是真的。

您需要使用的是 const enum因为这编译成一个字符串。

尝试更改为

export const enum Role {
Admin = 'admin',
User = 'user',
Engineer = 'engineer'
}

尽管这确实有其他含义。
https://www.typescriptlang.org/docs/handbook/enums.html#const-enums

而不是做一个 indexOf 你可以使用 .includes
route.data.roles.includes(currentUser.role)

编辑:
也可能是您的数据没有被继承到您尝试获取它的位置。

您可能需要将此添加到您的路由器配置中
RouterModule.forRoot([], {
initialNavigation: 'enabled',
paramsInheritanceStrategy: 'always', <-- this makes params and data accessible lower down into the tree
relativeLinkResolution: 'corrected',
scrollPositionRestoration: 'enabled',
}),

关于javascript - 具有很少 Angular 色访问权限的 Angular JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62022007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com