From 575124681901b72a460a99ed72cdd53ecc4bd485 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 9 Mar 2023 16:07:20 +0100 Subject: [PATCH] added guard --- .../docs/documentation/guards.md | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/site/angular-auth-oidc-client/docs/documentation/guards.md b/docs/site/angular-auth-oidc-client/docs/documentation/guards.md index 3b24a79cc..ea18c33f1 100644 --- a/docs/site/angular-auth-oidc-client/docs/documentation/guards.md +++ b/docs/site/angular-auth-oidc-client/docs/documentation/guards.md @@ -5,6 +5,8 @@ sidebar_position: 8 # Using Route Guards +## Class based + > Guards should only be applied to protected URLs. There should be no guard active on the default route where the authorization request is processed. Please refer to the auto-login guard in this repo as a reference. It is important that the callback logic can be run on a route without the guard running or run before the guard logic. @@ -51,3 +53,40 @@ const appRoutes: Routes = [ ``` All other guard types like `canLoad` or `canActivateChild` work in a similar way. However, the guard class has to implement the respective interfaces and methods accordingly. + +## Functional + +```ts +import { inject } from '@angular/core'; +import { Router } from '@angular/router'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; +import { map, take } from 'rxjs/operators'; + +export const isAuthenticated = () => { + const oidcSecurityService = inject(OidcSecurityService); + const router = inject(Router); + + return oidcSecurityService.isAuthenticated$.pipe( + take(1), + map(({ isAuthenticated }) => { + if (!isAuthenticated) { + router.navigate(['']); + + return false; + } + return true; + }) + ); +}; +``` + +```ts +const appRoutes: Routes = [ + { + path: 'protected', + component: , + canActivate: [isAuthenticated] + }, + // ... +]; +```