Protecting Routes With Auth Guard In Angular

  • Using your preferred code editor, create a new application in Angular.
ng new auth-guard-demo --routing
  • Open the newly formed project after generating it, and then from the terminal, type the following command to create two files for Auth and Authentication.
ng g service ./_service/auth-guard  
ng g service ./_service/authentication
  • Enter the following instructions to create two components.
ng g c home  
ng g c login
  • Add the code to the auth-guard.service.ts file by opening 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;  
    }  
} 
  • the authentication.service.ts file’s source code.
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);  
  }  
}
  • Add the code to the home.component.ts file by opening 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(['']);  
  }  
}
  • Home.component.html file code
<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 the file login.component.html.
<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>
  • Add the code to the app-routing.module.ts file by opening 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 { }
  • Open the index.html file and insert the bootstrap reference there to finish.
<!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 : 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories