Angular 5 Auth Guard and Route Guards - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Angular 5 Auth Guard and Route Guards

Angular 5 Auth Guard and Route Guards

In this tutorial you learn How to Implementing Auth Guard with Component less Route in Angular 5?
In this article, we take a look with few of the different types of guards and how to implement them for specific use-
1.      Maybe the user must authenticate and then login in the app.
2.      If user has logged in but is not authorized to navigate to the target component.
3.      We might ask the user if its ok to discard pending changes rather than save them.

There are 5 types of Route Guards we use in Angular.

  1. CanActivate
    This helps to decide whether the route can be activated or not.
  1. CanActivateChild
    This helps to decide whether child routes can be activated or not.
  1. CanDeactivate
    This helps to decide whether the route can be deactivated or not. Generally, this is used to warn a user if they are navigating from the component.
  1. Resolve
    This performs route data retrieval before any activation of the route.
  1. CanLoad
    Checks to see if the user can navigate to the module which is lazily loaded.
Let’s start how to Generate Guard, I am using Angular CLI command for generating Auth Guard on Angular 5 applications.

The Auth Guard implementation is quite simple and Auth Guard CLI command is –
ng generate guard auth



 Why Use Auth Guard in Angular 5?
The Auth Guard is used to redirect the user to the page they landed on before being forced to login.


D:\Angular\AngularMaterial>ng generate guard auth
  create src/app/auth.guard.spec.ts (346 bytes)
  create src/app/auth.guard.ts (401 bytes)


auth.guard.ts –
import { Injectable } from '@angular/core';
import { CanActivateActivatedRouteSnapshotRouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    nextActivatedRouteSnapshot,
    stateRouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return true;
  }
}
And

auth.guard.spec.ts –
import { TestBedasyncinject } from '@angular/core/testing';

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

describe('AuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuard]
    });
  });

  it('should ...'inject([AuthGuard], (guardAuthGuard=> {
    expect(guard).toBeTruthy();
  }));
});

Now, we generate the login component for using angular gourd –
D:\Angular\AngularMaterial>ng g component login
  create src/app/login/login.component.html (24 bytes)
  create src/app/login/login.component.spec.ts (621 bytes)
  create src/app/login/login.component.ts (265 bytes)
  create src/app/login/login.component.css (0 bytes)
  update src/app/app.module.ts (394 bytes)


And the app.module.ts looks like –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModuleFormGroupfrom '@angular/forms';
import {RouterModulefrom '@angular/router';

//MY COMPONENTS
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      path: ''component: AppComponentpathMatch: 'full' },
      path: 'register'component: RegisterComponent },
      path: 'login'component: LoginComponent}])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Now, Create Auth Service-
D:\Angular\AngularMaterial>ng g service AuthService
  create src/app/auth-service.service.spec.ts (405 bytes)
  create src/app/auth-service.service.ts (117 bytes)


Auth Service looks like- auth-service.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthServiceService {

   constructor(private routerRouter) { }

   //Set User Secure Token
  setSecureToken(secure_tokenstring) {
    localStorage.setItem("LoggedIn"secure_token)
  }

  //Set User Secure Token
  getSecureToken() {
    return localStorage.getItem("LoggedIn")
  }

  //Check User is LoggedIn or not!
  isLoggednIn() {
    return this.getSecureToken() !== null;
  }

  //Logout method
  logout() {
    localStorage.removeItem("LoggedIn");
    this.router.navigate(["login"]);
  }
}

Now, calling the login service methods to validate user on login components and it looks like – login.component.ts
import { ComponentOnInit } from '@angular/core';
import { FormBuilderValidators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthServiceService } from '../auth-service.service';

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

  //constructor initialization
  constructor(private fbuilderFormBuilder,
    private routeRouter,
    private authServiceAuthServiceService) {
      this.form = fbuilder.group({
        email: ['', [Validators.requiredValidators.email]],
        password: [''Validators.requiredValidators.minLength]
      });
  }

  //ngOnInit method
  ngOnInit() {
  }

  //This method use for Login
  login() {
    if (this.form.valid) {
      this.authService.setSecureToken(this.form.value.email)
      this.route.navigate(["dashboard"]);
    }
  }
}

 Now, coming to your Auth Gourd and use your Auth service to validate the users and returns your status –
import { Injectable } from '@angular/core';
import { CanActivateActivatedRouteSnapshotRouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {Routerfrom '@angular/router';
import { AuthServiceService } from './auth-service.service';

@Injectable()
export class AuthGuard implements CanActivate {

  //constructor initialization
  constructor(private authServiceAuthServiceService,   private routeRouter){  }

  canActivate(
    nextActivatedRouteSnapshot,
    stateRouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if(this.authService.isLoggednIn()){
        return true;
      }else{
        this.route.navigate(["login"]);
        return false;
      }
  }
}

You must add your Auth Service and Auth Guard in you app.module.ts and its looks like –

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModuleFormGroupfrom '@angular/forms';
import {RouterModulefrom '@angular/router';

//MY COMPONENTS
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';

import { AuthServiceService } from './auth-service.service';
import { AuthGuard } from './auth.guard';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      path: ''component: AppComponentpathMatch: 'full'canActivate: [AuthGuard] },
      path: 'register'component: RegisterComponent },
      path: 'login'component: LoginComponent}])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.