I'm trying to redirect to an unauthorized route when a role tries to access an unauthorized route, I'm using keycloack-angular lib:
npm install keycloak-angular keycloak-js
My Guard
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));
}
}
Routing:
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 },
];
CodePudding user response:
You haven't used the router instance to redirect to another route when access is not allowed. Call the navigate statement to redirect wherever you return false
:
if (!requiredRoles.every((role) => this.roles.includes(role))) {
this.router.navigate(['/']);
}