[英]AuthGuard canActivate with http request for roles
I have a strange situation. 我有一个奇怪的情况。 My AuthGuard is more complicated than usual. 我的AuthGuard比平常更复杂。 It's depending on authentication token + on user role. 这取决于身份验证令牌+用户角色。
So whenever canActivate is fired I have to check if the user is authenticated and then check if he has a permission to go to the route it wants. 因此,每当触发canActivate时,我都必须检查用户是否已通过身份验证,然后检查他是否有权转到所需的路由。
Permission checking is handled in backend so I'm only have to make request and get response, whether the user is permitted or no. 权限检查是在后端处理的,因此无论用户是否被允许,我都只需要发出请求并获得响应。
I don't know how to achieve this. 我不知道该如何实现。 Checking auth token is easy, but how to combine this with http request? 检查身份验证令牌很容易,但是如何将其与http请求结合使用? I don't know. 我不知道。 I tried many solutions, but always I get error or infinity waiting. 我尝试了许多解决方案,但总是遇到错误或无限等待。
Here is my code for canActivate method. 这是我的canActivate方法的代码。 Note that checkPermission
is http.get(...)
请注意, checkPermission
是http.get(...)
canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
return this.store.select('auth').pipe(
take(1),
map((state: State) => {
if (state.token) {
return this.checkPermission(state, route).pipe(
map(res => {
if (res) {
return true;
}
return false;
})
);
} else {
return false;
}
}));
}
use switchMap 使用switchMap
canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
return this.store.select('auth').pipe(
take(1),
switchMap((state: State) => {
if (state.token) {
return this.checkPermission(state, route);
} else {
return of(false);
}
}),
map(res => !!res)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.