feat: add Keycloak authentication integration and guard
This commit is contained in:
parent
aff058a29e
commit
fe8b1a1399
7 changed files with 95 additions and 3 deletions
42
src/app/service/auth.service.ts
Normal file
42
src/app/service/auth.service.ts
Normal file
|
@ -0,0 +1,42 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
import {
|
||||
ActivatedRouteSnapshot,
|
||||
Router,
|
||||
RouterStateSnapshot
|
||||
} from '@angular/router';
|
||||
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthGuard extends KeycloakAuthGuard {
|
||||
constructor(
|
||||
protected override readonly router: Router,
|
||||
protected readonly keycloak: KeycloakService
|
||||
) {
|
||||
super(router, keycloak);
|
||||
}
|
||||
|
||||
public async isAccessAllowed(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
) {
|
||||
// Force the user to log in if currently unauthenticated.
|
||||
if (!this.authenticated) {
|
||||
await this.keycloak.login({
|
||||
redirectUri: window.location.origin + state.url
|
||||
});
|
||||
}
|
||||
|
||||
// Get the roles required from the route.
|
||||
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;
|
||||
}
|
||||
|
||||
// Allow the user to proceed if all the required roles are present.
|
||||
return requiredRoles.every((role) => this.roles.includes(role));
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue