Skip to content

Commit

Permalink
Merge pull request #1711 from damienbod/added-docs-for-functional-rou…
Browse files Browse the repository at this point in the history
…te-guard

Added docs to use functional route guard
  • Loading branch information
FabianGosebrink committed Mar 9, 2023
2 parents 6217283 + 5751246 commit 807fc49
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions docs/site/angular-auth-oidc-client/docs/documentation/guards.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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: <yourComponent>,
canActivate: [isAuthenticated]
},
// ...
];
```

0 comments on commit 807fc49

Please sign in to comment.