Angular Authentication and Authorization

Angular Authentication and Authorization

This is just one way to implement secured pages, sections and site areas to users, groups and roles using Angular.

My thanks to my buddy Mosh

Content management systems, subscription sites, and just about any site where a user is required to log on to complete a private task (paying a bill, for example) requires that a part of the site be locked down and only be accessed by challenging a user for her credentials, ensuring the presence of an account and/or some further validation of the user's identity. The following Angular code describes how to do this, and it uses JSON Web tokens, Router redirects, the CanActivate interface, route guards, storing JSON tokens in the local storage of the user's browser, and more.

USAGE: The code below are components from the attached Angular application zip file. The only difference from the files in the .zip file vs what I've edited on screen are just comments; otherwise the code is the same. Download this zip file first, then run npm install from your terminal program (from the directory where you unzipped the file into). Next you can serve it ng serve. You'll be prompted for an email and a password - use "" and "1234" respectively.

Functionally it might appear that this application doesn't do much; there's not much to be displayed or seen. However the functionality lies in the login, the admin section being protected and the logout functionality.
import { Http } from "@angular/http";
import { Injectable } from "@angular/core";
import { tokenNotExpired, JwtHelper } from "angular2-jwt";
import "rxjs/add/operator/map";

export class AuthService {
  currentUser: any;

  constructor(private http: Http) {
    let token = localStorage.getItem("token");
    if (token) {
      let jwt = new JwtHelper();
      this.currentUser = jwt.decodeToken(token);

  login(credentials) {
    return this.http
      .post("/api/authenticate", JSON.stringify(credentials))
      .map(response => {
        let result = response.json();

        if (result && result.token) {
          //store the token value that's returned from the server on the user's 
		  //machine (localStorage)
          localStorage.setItem("token", result.token);

          let jwt = new JwtHelper();
          this.currentUser = jwt.decodeToken(localStorage.getItem("token"));

          return true;
        } else return false;

  logout() {
    //to "log out" we remove the token from the user's localStorage
    this.currentUser = null;

  isLoggedIn() {
    //if token is not expired then user is logged in
    return tokenNotExpired("token");

import { AuthService } from "./services/auth.service";
import { Injectable } from "@angular/core";
import { Router, CanActivate } from "@angular/router";

// all you need in order to create a route guard is a class that implements the 
//CanActivate interface
export class AuthGuard implements CanActivate {
  constructor(protected router: Router, protected authService: AuthService) {}

  //ROUTE GUARD - stops user from being able to navigate to a protected route 
  //if they aren't logged in.
  //Use the canActivate() to push the user around
  canActivate() {
    if (this.authService.isLoggedIn()) return true;


    return false;

<h1>Home Page</h1>
<p *ngIf="authService.isLoggedIn()">
  Welcome {{ }}
  <!--standard interpolation to retrieve user's name, only display if logged in-->
  <!--check if user is logged in AND if user is an admin-->
  <li *ngIf="authService.isLoggedIn() && authService.currentUser.admin">
    <a routerLink="/admin">Admin</a>
  <li *ngIf="!authService.isLoggedIn()"><a routerLink="/login">Login</a></li>
  <li *ngIf="authService.isLoggedIn()">
    <a (click)="authService.logout()">Logout</a>

Link your website to this page! Copy and paste the URL below: