Angular 和 KeyCloak - 当角色无权访问时重定向到路由
Angular and KeyCloack - Redirect to route when role is not authorized to acess
当角色试图访问未经授权的路由时,我正在尝试重定向到未经授权的路由,
我正在使用 keycloack-angular lib:
npm install keycloak-angular keycloak-js
我的守卫
export class AuthGuard extends KeycloakAuthGuard {
constructor(
protected readonly router: Router,
protected readonly keycloak: KeycloakService
) {
super(router, keycloak);
}
public async isAccessAllowed(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url,
});
}
const requiredRoles = route.data.roles;
if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
return true;
} else {
if (!this.roles || this.roles.length === 0) {
return false;
}
}
return requiredRoles.every((role) => this.roles.includes(role));
}
}
路由:
const routes: Routes = [
...
{
path: 'testar',
loadChildren: () =>
import('./core/modules/testar/testar.module').then((m) => m.TestarModule),
canActivate: [AuthGuard],
data: { roles: ['admin', 'user'] }
},
{ path: 'notauthorized', component: NotauthorizedComponent },
];
您没有使用路由器实例在不允许访问时重定向到另一个路由。调用 navigate 语句重定向到任何地方 return false
:
if (!requiredRoles.every((role) => this.roles.includes(role))) {
this.router.navigate(['/']);
}
当角色试图访问未经授权的路由时,我正在尝试重定向到未经授权的路由, 我正在使用 keycloack-angular lib:
npm install keycloak-angular keycloak-js
我的守卫
export class AuthGuard extends KeycloakAuthGuard {
constructor(
protected readonly router: Router,
protected readonly keycloak: KeycloakService
) {
super(router, keycloak);
}
public async isAccessAllowed(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url,
});
}
const requiredRoles = route.data.roles;
if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
return true;
} else {
if (!this.roles || this.roles.length === 0) {
return false;
}
}
return requiredRoles.every((role) => this.roles.includes(role));
}
}
路由:
const routes: Routes = [
...
{
path: 'testar',
loadChildren: () =>
import('./core/modules/testar/testar.module').then((m) => m.TestarModule),
canActivate: [AuthGuard],
data: { roles: ['admin', 'user'] }
},
{ path: 'notauthorized', component: NotauthorizedComponent },
];
您没有使用路由器实例在不允许访问时重定向到另一个路由。调用 navigate 语句重定向到任何地方 return false
:
if (!requiredRoles.every((role) => this.roles.includes(role))) {
this.router.navigate(['/']);
}