Here, today we will learn about protecting our routes with Auth guard in Angular 7. As we all know that our system should be secure i.e. without proper authentication no one should access the protected information of our web application.

So the question is how we can avoid this scenario that is no one can access the sensitive information without proper authentication. This can be achieved by the use of Auth guard in Angular 7.

Auth-guard makes use of CanActivate interface and it checks for if the user is logged in or not. If it returns true than the execution for the requested route will continue, and if return false that the requested route will be kicked off and the default route will be shown.

Create a new application in Angular 7 by using your favourite code editor.

ng new auth-guard-demo --routing

After creating, open the newly created project and from terminal create two files for Auth and Authentication by typing the following command.

ng g service ./_service/auth-guard
ng g service ./_service/authentication

Create two components by typing the following commands.

ng g c home
ng g c login

Open the auth-guard.service.ts file and add the code in it.

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(private _router: Router) { }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            return true;
        }

        this._router.navigate(['']);
        return false;
    }
}

Code for authentication.service.ts file

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  login(username: string, password: string) {
    if (username == "admin" && password == "admin") {
      localStorage.setItem('currentUser', "loggedin");
      return true;
    }
  }

  logout() {
    localStorage.removeItem('currentUser');
  }

  public get loggedIn(): boolean {
    return (localStorage.getItem('currentUser') !== null);
  }

}

Open the home.component.ts file and add the code in it.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../_service/authentication.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private router: Router, private authenticationService: AuthenticationService) { }

  ngOnInit() {
  }
  
  logout() {
    this.authenticationService.logout();
    this.router.navigate(['']);
  }
}

Code for home.component.html file

<div class="container">
  <h1>You are successfully logged in</h1>
  <button (click)="logout()" class="btn btn-danger">Logout</button>
</div>

Open the login.component.ts file and add the code in it.

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../_service/authentication.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

  username: string;
  password: string;
  title = 'auth-guard-demo';
  constructor(private _auth: AuthenticationService, private _router: Router) {
    if (this._auth.loggedIn) {
      this._router.navigate(['home']);
    }
  }

  login(): void {
    if (this.username != '' && this.password != '') {
      if (this._auth.login(this.username, this.password)) {
        this._router.navigate(["home"]);
      }
      else
        alert("Wrong username or password");
    }
  }

}

Code for login.component.html file

<div class="container">
  <div class="row">
    <div class="form-group col-md-12">
      <label>Username</label>
      <input type="text" [(ngModel)]="username" name="username" class="form-control" />
    </div>
    <div class="form-group col-md-12">
      <label>Password</label>
      <input type="password" [(ngModel)]="password" name="password" class="form-control" />
    </div>
    <div class="form-group col-md-3">
      <button (click)="login()" class="btn btn-success">Login</button>
    </div>
  </div>
</div>

Open the app-routing.module.ts file and add the code in it.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AuthGuard } from './_service/auth-guard.service';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard],
    data: {
      title: 'Home' 
    }
  },
  {
    path: 'login',
    component: LoginComponent,
    data: {
      title: 'Login'
    }
  },
  {
    path: '',
    component: LoginComponent,
    data: {
      title: 'Login'
    }
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Code for app.component.ts file

<router-outlet></router-outlet>

Place the dependencies in app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthenticationService } from './_service/authentication.service';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
  ],
  providers: [AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Finally. open the index.html file and add the bootstrap reference in it.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AuthGuardDemo</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Output:

output