Angular Authentication: Securing Routes with Route Guards

Where to store your route guard

src
|_ app
|_ ...
|_ auth
|_ auth.guard.ts
|_ auth.service.ts

Creating the route guard

Generate the route guard

ng generate guard auth/auth
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return true;
}
}

Determining the user’s authenticated state

Creating an isAuthenticated function

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { } isAuthenticated() {
return this.http.get('/auth/isAuthenticated');
}
}

Using isAuthenticated() in your route guard

...
import { AuthService } from './auth.guard';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
... constructor(private authService: AuthService,
private router: Router) { }
...
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
... canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isAuthenticated().pipe(map((response: { authenticated: boolean}) => {
if (response.authenticated) {
return true;
}
this.router.navigate(['/login']);
return false;
}), catchError((error) => {
this.router.navigate(['/login']);
return of(false);
}));
}
}

Add your guard to your routes

...
import { AuthGuard } './auth/auth.guard';
const routes: Routes = [
...
{
path: 'profile',
component: ProfileComponent,
canActivate: [ AuthGuard ]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [ AuthGuard ]
})
export class AppRoutingModule { }

Final Thoughts

--

--

--

Full-stack software engineer specializing in web and mobile development. Always learning new things. “There is no growth in the comfort zone…”

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript Problems & it’s solution

How to Use React Native Geolocation to Get Postal Address

Exposing HomeObject

To learn JavaScript

E2E Testing on Angular App with Protractor ( tips included)

Node.js Zlib Module

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jacob Neterer

Jacob Neterer

Full-stack software engineer specializing in web and mobile development. Always learning new things. “There is no growth in the comfort zone…”

More from Medium

Angular proxy configuration for API calls

Azure AD with Angular and Express.js

Creating and Build a Desktop Application with Angular and Electron

Angular with clean URL’s using Apache’s mod_rewrite