Protect Routes

Protect routes using Angular authentication guards

Create a new angular guard that will protect the profile route to only allow authenticated users to access the profile (And redirect to a login page otherwise):

            ng generate guard auth
            ? Which interfaces would you like to implement? CanActivate
            CREATE src/app/auth.guard.spec.ts (331 bytes)
            CREATE src/app/auth.guard.ts (456 bytes)

Open auth.guard.ts and add the following code:

            import { Injectable } from '@angular/core';
            import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
            import { Observable } from 'rxjs';
            import { OAuthService } from 'angular-oauth2-oidc';
            import { AuthService } from './auth.service';
              providedIn: 'root'
            export class AuthGuard implements CanActivate {
                  private authService: AuthService) { }
                next: ActivatedRouteSnapshot,
                state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
                    if (this.authService.hasValidIdToken()) {
                        return true;
                    return false;

Now open app-routing.module.ts and update the profile route to use the guard:

    import { AuthGuard } from './auth.guard';

    const routes: Routes = [
        { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard]},
        { path: 'logout', component: LogoutComponent},
        { path: 'callback', component: RedirectComponent},
        { path: '**', component: PagenotfoundComponent}

Update app.module.ts with the appropriate providers and modules:

  • Add the HttpClientModule and OAuthModule configuration within the imports section. The resourceServer configuration will ensure that all HTTP requests to the configured allowedUrls will have the access token automatically added via the Authorization header
  • Add the AuthGuard within the providers section
            import { OAuthModule } from 'angular-oauth2-oidc';
            import { AuthGuard } from './auth.guard';
            import { HttpClientModule } from '@angular/common/http';
            declarations: [
            imports: [
                resourceServer: {
                        allowedUrls: ['http://localhost:9090'],
                        sendAccessToken: true
            providers: [AuthGuard],
            bootstrap: [AppComponent]
            export class AppModule { }

Open redirect.component.ts and add the following code to conduct the exchange and re-direct to the profile page after the token is received:

            import { Component, OnInit } from '@angular/core';
            import { AuthService } from '../auth.service';

                selector: 'app-redirect',
                templateUrl: './redirect.component.html',
                styleUrls: ['./redirect.component.scss']
            export class RedirectComponent implements OnInit {
                ngOnInit(): void {
                constructor(private authService: AuthService) { }

The application will now redirect to the profile page with the JWT access and id tokens being stored in session storage.

Next Steps

Display User Information