new authorization approach

This commit is contained in:
2024-05-22 11:05:40 -05:00
parent 8fba3aa832
commit 0b7e33612a
23 changed files with 47 additions and 867 deletions

View File

@@ -1,105 +1,24 @@
// import { inject } from '@angular/core';
// import { CanMatchFn, Router, UrlTree } from '@angular/router';
import { Injectable } from '@angular/core';
import { Router, UrlTree } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
import { KeycloakInitializerService } from '../services/keycloak-initializer.service';
// // Services
// import { KeycloakInitializerService } from '../services/keycloak-initializer.service';
// import { KeycloakService } from '../services/keycloak.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 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);
// keycloakService.login({
// redirectUri: `${window.location.origin}${segments['url']}`,
// });
// }
// // Get the user Keycloak roles and the required from the route
// 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
// if (!Array.isArray(requiredRoles) || requiredRoles.length === 0) {
// return true;
// }
// const authorized = requiredRoles.every(role => roles.includes(role));
// if (authorized) {
// return true;
// }
// return router.createUrlTree(['/home']);
// };
/**
* @license
* Copyright Mauricio Gemelli Vigolo and contributors.
*
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
*/
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
/**
* A simple guard implementation out of the box. This class should be inherited and
* implemented by the application. The only method that should be implemented is #isAccessAllowed.
* The reason for this is that the authorization flow is usually not unique, so in this way you will
* have more freedom to customize your authorization flow.
*/
export class KeycloakAuthGuard implements CanActivate {
/**
* Indicates if the user is authenticated or not.
*/
protected authenticated: boolean;
/**
* Roles of the logged user. It contains the clientId and realm user roles.
*/
protected roles: string[];
constructor(protected router: Router, protected keycloakAngular: KeycloakService) {}
/**
* CanActivate checks if the user is logged in and get the full list of roles (REALM + CLIENT)
* of the logged user. This values are set to authenticated and roles params.
*
* @param route
* @param state
*/
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
try {
this.authenticated = await this.keycloakAngular.isLoggedIn();
this.roles = await this.keycloakAngular.getUserRoles(true);
return await this.isAccessAllowed(route, state);
} catch (error) {
throw new Error('An error happened during access validation. Details:' + error);
}
@Injectable({
providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
constructor(protected override readonly router: Router, protected readonly keycloak: KeycloakService, private keycloakInitializer: KeycloakInitializerService) {
super(router, keycloak);
}
/**
* Create your own customized authorization flow in this method. From here you already known
* if the user is authenticated (this.authenticated) and the user roles (this.roles).
*
* Return a UrlTree if the user should be redirected to another route.
*
* @param route
* @param state
*/
async isAccessAllowed(route, state): Promise<boolean | UrlTree> {
if (!this.authenticated) {
async isAccessAllowed(): Promise<boolean | UrlTree> {
if (!this.keycloakInitializer.isInitialized()) {
await this.keycloakInitializer.initialize();
}
const authenticated = this.keycloak.isLoggedIn();
if (!authenticated) {
await this.router.navigate(['/home']);
}
return this.authenticated;
return authenticated;
}
}