In this article, we will check how to use token based authentication with Web.API in angular
So, let’s See below example here,
Step 1:-
Create a Web API Project and create a class.
using System.ComponentModel.DataAnnotations; namespace demo.modules { public class LoginDto { [Required] public string Email { get; set; } [Required] public string Password { get; set; } } }
Step 2:-
Add the following package to your project
Microsoft.IdentityModel.Tokens System.IdentityModel.Tokens.Jwt
Step 3:-
Create an interface in your project and add below code
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace demo.Interface { public interface IUserService { Task<string> LoginAuthenticate(string email, string password); } }
Step 4:-
Create service in your project and add below code
using demo.Interface; using System; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using Microsoft.Extensions.Options; using System.Threading.Tasks; using Iris.API.Helpers; using System.Text; namespace demo.Service { public class UserService : IUserService { private IOptions<AppSettings> _appSettings; public UserService(IOptions<AppSettings> appSettings) { _appSettings = appSettings; } public async Task<string> LoginAuthenticate(string email, string password) { var userEntity = false; if (email == "admin@mail.com" && password == "Test@123") { userEntity = true; } if (userEntity == false) return "sorry"; var tokenHandler = new JwtSecurityTokenHandler(); string appSecret = _appSettings.Value.Secret; var key = Encoding.ASCII.GetBytes(appSecret); var tokenDescriptor = new SecurityTokenDescriptor { Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } }
Step 5:-
Create controller in your project and add below code
using demo.Interface; using demo.modules; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace demo.Controllers { public class UserController : ControllerBase { private readonly IUserService _userService; public UserController(IUserService userService) { _userService = userService; } [AllowAnonymous] [HttpPost("LoginAuthenticate")] public async Task<ActionResult<string>> LoginAuthenticate([FromBody] LoginDto loginModel) { return await _userService.LoginAuthenticate(loginModel.Email, loginModel.Password); } } }
Step 6:-
Create an angular application using following command
ng new domo cd domo
Step 7:-
Create login and employee component using following command
ng g c login ng g c employee-master
Step 8:-
Create auth.guard.ts file and add following code
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { EmployeeService } from './employee.service'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { username:any; password:any; constructor(private employeeservice:EmployeeService,private router:Router){} canActivate(): boolean { var tocken = localStorage.getItem('tocken'); if(tocken){ return true; } else { this.router.navigate(['login']); return true; } } }
Step 9:-
Create tockeninterceptor service and add following code
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,HttpResponse,HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { EmployeeService } from './employee.service'; import { AuthGuard } from './auth.guard'; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class TockeninterceptorService implements HttpInterceptor { constructor(private EmployeeService:EmployeeService,public auth:AuthGuard,private router:Router) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { var gettocken = localStorage.getItem("tocken"); console.log("interceptor: " + gettocken); const getdata = gettocken; if(getdata) { req = req.clone({ setHeaders: { Authorization: 'Bearer ' + JSON.parse(getdata) } }); } return next.handle(req).pipe( catchError((error: HttpErrorResponse)=>{ let errorMsg = ''; let data = {}; if(error.error instanceof ErrorEvent) { console.log("This is client side error"); errorMsg = `Error: ${error.error.message}`; } else { switch(error.status) { case 401: alert(error.status); debugger data = { status:error.status } this.router.navigate(['login']); break; case 403: this.router.navigate(['login']); break; case 404: alert(error.status); this.router.navigate(['notfound']); break; } console.log('this is server side error'); errorMsg = `Error Code: ${error.status}, Message: ${error.message}`; } console.log(errorMsg); return throwError(errorMsg); }) ) } }
Step 10:-
Create employee service and add following code
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { Observable } from 'rxjs'; import { Country } from './Country'; import { City } from './City'; @Injectable({ providedIn: 'root' }) export class EmployeeService { public isDialogOpen: Boolean = false; flag: any = true; fDate: any; baseURL = environment.apiURL; constructor(private http: HttpClient) { } getTocken(userName: string, passWord: string): Observable<any> { debugger let _requestObj = { "email": userName, "password": passWord } return this.http.post<any>(`${this.baseURL}/User/LoginAuthenticate`, _requestObj); } getEmployee(): Observable<Employee_Mst[]> { return this.http.get<Employee_Mst[]>(`${this.baseURL}/api/User/GetAllUsers`) } isUserLogIn() { return this.flag; } } export class Employee_Mst { public id!: number; public name!:string; public dob!:Date; public gender!:string; public phoneNo!:string; public address!:string; public emailId!:string; public designation!:string; public hobbies!:string; public salary!:string; public country!:number; public city!:number; public image!:string; public password!:string; }
Step 11:-
Add following code in app.modules.ts file
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { EmployeesMasterComponent } from './employees-master/employees-master.component'; import { TockeninterceptorService } from './tockeninterceptor.service'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { DatePipe } from '@angular/common'; import { AuthGuard } from './auth.guard'; import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, EmployeesMasterComponent, PagenotfoundComponent ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule, HttpClientModule ], providers: [{provide:HTTP_INTERCEPTORS,useClass:TockeninterceptorService,multi:true},DatePipe,AuthGuard], bootstrap: [AppComponent] }) export class AppModule { }
Step 12:-
Add following code in app-routing.module.ts file
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { EmployeesMasterComponent } from './employees-master/employees-master.component'; import { LoginComponent } from './login/login.component'; import { AuthGuard } from './auth.guard'; const routes: Routes = [ {path: '',component:LoginComponent,canActivate:[AuthGuard]}, {path: 'login',component:LoginComponent}, {path: 'employee',component:EmployeesMasterComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Step 13:-
Add following code in login.component.html file
<div class="container" style="padding-left: 200px;padding-right: 200px;"> <form [formGroup]="loginForm" (ngSubmit)="onSubmit()"> <div style="margin-top:25%;background-color: lightgray;border-radius: 10px;padding-top: 20px;padding-bottom: 20px;padding-left: 173px;padding-right: 212px;box-shadow: 10px 10px 8px black;"> <div class="row"> <div class="col-lg-12 text-center"> <h2>Login</h2> </div> <div class="col-lg-12" style="margin-top:10px"> <!--<label>UserName:</label>--> <input type="text" id="UserName" class="form-control" formControlName="UserName" placeholder="Enter UserName"> </div> <div class="col-lg-12" style="margin-top:10px"> <!--<label>Password:</label>--> <input type="password" id="PassWord" class="form-control" formControlName="PassWord" placeholder="Enter Password"> </div> <div class="col-lg-12" style="margin-top:30px"> <button type="submit" class="form-control">Login</button> </div> </div> </div> </form> </div>
Step 14:-
Add following code in login.component.ts file
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { EmployeeService } from '../employee.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm!: FormGroup; constructor(private fb: FormBuilder, private employeeService: EmployeeService, private router: Router) { } ngOnInit(): void { this.loginForm = this.fb.group({ UserName: ['', Validators.required], PassWord: ['', Validators.required] }); } get loginData() { return this.loginForm.controls; } onSubmit() { var userName = ((this.loginForm.value).UserName); var passWord = ((this.loginForm.value).PassWord); this.employeeService.getTocken(userName, passWord).subscribe((response: any) => { if (response.isSuccess) { localStorage.setItem("tocken", JSON.stringify(response.tocken)); this.router.navigate(['/employee']); } }) } }
Step 15:-
Add following code in employees-master.component.html file
<!-- Modal --> <div> <!--grid--> <div class="row" style="margin-top: 10px;"> <div class="col-lg-2"></div> <div class="col-lg-8"> <!-- <button type="button" class="btn btn-lg btn-outline-primary" data-toggle="modal" data-target="#myModal" (click)="showModal=true">Add Employee</button>--> <table class="table-striped table-hover"> <tr style="background-color: rgb(43, 42, 42);color: white;"> <th class="set-padding">Name</th> <th class="set-padding">DOB</th> <th class="set-padding">Gender</th> <th class="set-padding">PhoneNo</th> <th class="set-padding">Address</th> <th class="set-padding">EmailId</th> <th class="set-padding">Designation</th> <th class="set-padding">Salary</th> </tr> <tr> <td>Siddharth</td> <td>21/06/1994</td> <td>Male</td> <td>9999995555</td> <td>abc</td> <td>abc@gmail.com</td> <td>CEO</td> <td>-</td> </tr> <tr> <td>Aaliya</td> <td>21/06/1995</td> <td>Female</td> <td>9999995555</td> <td>abcd</td> <td>abcd@gmail.com</td> <td>Employee</td> <td>-</td> </tr> </table> </div> <div class="col-lg-2"></div> </div> </div>
Step 16:-
Run your application
npm start