Initial commit
This commit is contained in:
60
src/app/guards/auth.guard.ts
Normal file
60
src/app/guards/auth.guard.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { AuthGuardData, createAuthGuard, KeycloakService } from 'keycloak-angular';
|
||||
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { appConfig } from '../../app.config';
|
||||
import Keycloak from 'keycloak-js';
|
||||
|
||||
/**
|
||||
* The logic below is a simple example, please make it more robust when implementing in your application.
|
||||
*
|
||||
* Reason: isAccessGranted is not validating the resource, since it is merging all roles. Two resources might
|
||||
* have the same role name, and it makes sense to validate it more granular.
|
||||
*/
|
||||
const isAccessAllowed = async (
|
||||
route: ActivatedRouteSnapshot,
|
||||
__: RouterStateSnapshot,
|
||||
authData: AuthGuardData
|
||||
): Promise<boolean | UrlTree> => {
|
||||
const marker_start = '======================= auth.guard >>> =======================';
|
||||
const marker_end = '\n======================= <<< auth.guard =======================';
|
||||
console.debug(marker_start);
|
||||
|
||||
const { authenticated, grantedRoles } = authData;
|
||||
console.debug('authData', authData);
|
||||
// console.debug('authenticated', authenticated);
|
||||
// console.debug('grantedRoles', grantedRoles);
|
||||
// console.debug('grantedRoles - realmRoles', grantedRoles.realmRoles);
|
||||
// console.debug('grantedRoles - resourceRoles', grantedRoles.resourceRoles);
|
||||
|
||||
const requiredRole = route.data['role'];
|
||||
// console.debug('requiredRole', requiredRole);
|
||||
|
||||
if (!requiredRole) {
|
||||
// console.debug('No role required for this route.');
|
||||
return false;
|
||||
}
|
||||
|
||||
const router = inject(Router);
|
||||
const notAllowed = router.parseUrl('/auth/access');
|
||||
const keycloak = inject(Keycloak);
|
||||
|
||||
if (!authenticated) {
|
||||
console.debug('you are not authenticated. please authenticate first.' + marker_end);
|
||||
// await keycloak.login({ redirectUri: window.location.href });
|
||||
return notAllowed;
|
||||
}
|
||||
|
||||
const hasRequiredRealmRole = requiredRole.some((role: string) => {
|
||||
return grantedRoles.realmRoles.includes(role);
|
||||
});
|
||||
if (hasRequiredRealmRole) {
|
||||
console.debug('you have the required realm role' + marker_end);
|
||||
return true;
|
||||
}
|
||||
|
||||
console.debug('you do not have permission to visit this page.' + marker_end);
|
||||
return notAllowed;
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
export const canActivateAuthRole = createAuthGuard<CanActivateFn>(isAccessAllowed);
|
||||
Reference in New Issue
Block a user