angular auth guard example
Routes enable the user to navigate through the application. Sometimes the user needs to do something before being allowed access to a certain part of the application—for example, log in. Route guards can be used to control access to certain routes.
There are two main types of route guards:
• CanActivate: Can the user navigate to a route? In this class, you can inject the router. This is useful to navigate the user a way to another resource if the user isn’t allowed to navigate to a route.
• CanDeactivate: Can the user move away from a route? Useful for prompting to save changes.
They are following ways of authentication
CanActivate
CanActivateChild
CanDeactivate
CanLoad
Resolve
Example
Write following code into app.module.ts
const routes : Routes = [ { path: "", component : HomeComponent }, { path: "myhome", component : HomeComponent }, { path: "contact", component : ContactUsComponent }, { path: "dashboard", canActivate : [AuthGuard] , component: DashboardComponent }, { path: "login", component : LoginComponent }, { path: "lazy1", loadChildren: 'app/lazy/lazy.module#LazyModule' } ]
Step 2: Create two components login and dashboard.
Step 3: Create new guard using ng g guard auth
Step 4: create new service myservice.
Step 5: Set provides in app.module.ts
providers: [AuthGuard],
import { RouterModule , Router } from '@angular/router'; import { MyserviceService } from './../myservice.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], providers: [MyserviceService] }) export class LoginComponent implements OnInit { constructor(private service : MyserviceService , private routes: Router) { } msg; ngOnInit() { } check(uname: string, p : string) { var output = this.service.checkusernameandpassword(uname, p); if(output == true) { this.routes.navigate(['/dashboard']); } else{ this.msg ='Invalid username or password'; } } }
<p> login works! </p> <input type="text" #u1 /><br> <input type="password" #p2 /><br/> <button (click)="check(u1.value, p2.value)">Login</button> <br/> <span>{{ msg }}</span>
import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { constructor() { } checkusernameandpassword(uname: string, pwd : string) { if(uname == "admin" && pwd =="admin123"){ localStorage.setItem('username',"admin"); return true; } else{ return false; } } }
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot , Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; @Injectable() export class AuthGuard implements CanActivate { constructor(private routes : Router){} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if(localStorage.getItem('username')!= null){ return true; } else { this.routes.navigate(['/login']); return false; } } }
Output :
Shweta