new initialization process, keycloak update 24.0.4
This commit is contained in:
@@ -1,22 +1,30 @@
|
||||
import { CanMatchFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { CanMatchFn, Router, UrlTree } from '@angular/router';
|
||||
|
||||
// Services
|
||||
import { UserService } from '../services/user.service';
|
||||
|
||||
import { KeycloakInitializerService } from '../services/keycloak-initializer.service';
|
||||
import { KeycloakService } from '../services/keycloak.service';
|
||||
import { createLogger } from '../utils/utils';
|
||||
const logger = createLogger('authGuard');
|
||||
export const authGuard: CanMatchFn = async (route, segments): Promise<boolean | UrlTree> => {
|
||||
const router = inject(Router);
|
||||
const userService = inject(UserService);
|
||||
|
||||
const authenticated: boolean = userService.isLoggedIn();
|
||||
const keycloakService = inject(KeycloakService);
|
||||
const keycloakInitializer = inject(KeycloakInitializerService);
|
||||
if (!keycloakInitializer.isInitialized()) {
|
||||
await keycloakInitializer.initialize();
|
||||
}
|
||||
logger.info('###-> calling isLoggedIn()');
|
||||
const authenticated = keycloakService.isLoggedIn();
|
||||
if (!authenticated) {
|
||||
console.log(window.location.origin)
|
||||
console.log(window.location.href)
|
||||
await userService.login(`${window.location.origin}${segments['url']}`);
|
||||
console.log(window.location.origin);
|
||||
console.log(window.location.href);
|
||||
keycloakService.login({
|
||||
redirectUri: `${window.location.origin}${segments['url']}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Get the user Keycloak roles and the required from the route
|
||||
const roles: string[] = userService.getUserRoles();//keycloakService.getUserRoles(true);
|
||||
const roles: string[] = keycloakService.getUserRoles(true);
|
||||
const requiredRoles = route.data?.['roles'];
|
||||
|
||||
// Allow the user to proceed if no additional roles are required to access the route
|
||||
@@ -24,15 +32,11 @@ export const authGuard: CanMatchFn = async (route, segments): Promise<boolean |
|
||||
return true;
|
||||
}
|
||||
|
||||
// Allow the user to proceed if ALL of the required roles are present
|
||||
const authorized = requiredRoles.every((role) => roles.includes(role));
|
||||
// Allow the user to proceed if ONE of the required roles is present
|
||||
//const authorized = requiredRoles.some((role) => roles.includes(role));
|
||||
const authorized = requiredRoles.every(role => roles.includes(role));
|
||||
|
||||
if (authorized) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Display my custom HTTP 403 access denied page
|
||||
return router.createUrlTree(['/access']);
|
||||
};
|
||||
return router.createUrlTree(['/home']);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user