JWT Authentication & Authorization With .NET Core & Angular

Kindly check below article if you are not familiar with JWT token how it is generated in .net core.

This article is an extension to a previous article where we are going to see how we can use generated JWT token with angular so stay tuned and follow the below steps if you want to use JWT token in your application,

Step 1 Create an angular application with .net Core.

Go to visual studio 2019 -> Create New Project -> Asp.Net Core Web Application -> Select Angular Template -> Finish.

Check the image below so if you see project ClientApp folder contains all your angular code.

Project Structure

Step 2 — Add JWT token generation logic in .net core side by checking previous logic.

Step 3 — Once the token generation API is written now you need to fetch that token on the angular side. For getting a token in angular side write required calls and services which are going to communicate with your token generation call endpoint.

Service.ts

import { Component, OnInit, Inject } from ‘@angular/core’;import { HttpClient, HttpHeaders, HttpErrorResponse, HttpParams } from ‘@angular/common/http’;import { Injectable } from ‘@angular/core’;import { map, catchError } from ‘rxjs/operators’;import { Observable, of, throwError } from ‘rxjs’;@Injectable({providedIn: ‘root’})export class Service {_baseURL: string;errorMsg: string;usertoken: any;private headers: HttpHeaders;constructor(private http: HttpClient, @Inject(‘BASE_URL’) baseUrl: string) {this._baseURL = baseUrl;}ngOnInit() {}GET(url: string): Observable<any> {return this.http.get(this._baseURL + url);}GETWithParams(url: string, params: HttpParams): Observable<any> {return this.http.get(this._baseURL + url, { params: params, headers: this.headers });}GETWithToken(url: string): Observable<any> {this.usertoken = sessionStorage.getItem(“token”);return this.http.get(this._baseURL + url, {headers: new HttpHeaders().set(‘Authorization’, “Bearer “ + this.usertoken)}).pipe(catchError(error => {if (error.error instanceof ErrorEvent) {this.errorMsg = `Error: ${error.error.message}`;} else {this.errorMsg = `Error: ${error.error.message}`; }return throwError(this.errorMsg);}));}POST(url: string, params: any): Observable<any> {this.usertoken = sessionStorage.getItem(“token”);return this.http.post(this._baseURL + url, params);}}

TokenGen.ts

import { Component, OnInit, Inject } from ‘@angular/core’;import { HttpClient, HttpHeaders, HttpErrorResponse, HttpParams } from ‘@angular/common/http’;import { Injectable } from ‘@angular/core’;import { Service } from ‘./service’;import { User } from ‘../Model/User’;@Injectable({providedIn: ‘root’})export class TokenGen {constructor(private http: HttpClient, private service: Service) {}GetToken(userInfo: User) {return this.service.POST(‘api/Login/loginfo’, userInfo);}GetData() {return this.service.GETWithToken(‘api/weatherforecast’);}}

Step 4 — Once service is ready next step is to call token generation method on your login component as below,

home.component.html

<form #userForm=”ngForm” *ngIf=”!unauthorized”><div class=”row form-group”><div class=” col-md-3"><label class=”lblUserName” for=”UserName”>User Name</label></div><div class=”col-md-3"><input type=”text”name=”username” #username=”ngModel” [(ngModel)]=”UserInformation.username” required></div><div class=” col-md-3"><label class=”lblPassword” for=”Password”>Password</label></div><div class=”col-md-3"><input type=”text”name=”password” #password=”ngModel” [(ngModel)]=”UserInformation.password” required></div></div><div class=”row form-group” style=”text-align:right”><button class=”btn btn-primary” type=”button” (click)=”Login(userForm)”>Login</button></div></form><div class=”row form-group” style=”text-align:center”>{{successMessage}}</div>

home.component.ts

import { Component } from ‘@angular/core’;import { NgForm } from ‘@angular/forms’;import { User } from ‘../Model/User’;import { TokenGen } from ‘../Service/tokenGen’;@Component({selector: ‘app-home’,templateUrl: ‘./home.component.html’,})export class HomeComponent {UserInformation: User;userInfo: User;unauthorized: boolean;successMessage: string;constructor(private tokenGen: TokenGen) {}ngOnInit() {this.UserInformation = new User();}Login(UserInformation: NgForm) {this.tokenGen.GetToken(this.UserInformation).subscribe(response => {this.userInfo = response;if (response == null) {this.unauthorized = true;this.successMessage = “Wrong Credentials.”}else {sessionStorage.setItem(“token”, this.userInfo.token);this.unauthorized = false;this.successMessage=”You are logged in successfully now you can fetch the data from weatherforecast api.”}});}}

If you can see here an important thing is like once the user is authenticated and token is received we are storing that token in SessionStorage which will be used for further communication calls.

You can store this token in LocalStorage or SessionStorage please checkout the difference below,

Session storage value will persist for a particular page or session only and will not be available on any other page but local storage value once entered can be accessed on any page. If you are closing the browser SessionStorage value is not available while local storage value is still there. So in a nutshell LocalStorage value is there still the user cant delete it. while SessionStorage value clears it up if you are closing the browser or tab.

Step 5- Once you have that token you can use it for further calls with Web Api.

You need to send this token in every http request with http header as bearer token. Please check above service code for how to send the token in header.

fetch-data.component.ts

import { Component, Inject } from ‘@angular/core’;import { HttpClient } from ‘@angular/common/http’;import { TokenGen } from ‘../Service/tokenGen’;@Component({selector: ‘app-fetch-data’,templateUrl: ‘./fetch-data.component.html’})export class FetchDataComponent {public forecasts: WeatherForecast[];constructor(private tokenGen: TokenGen) {this.tokenGen.GetData().subscribe(result => {this.forecasts = result;}, error => console.error(error));}}interface WeatherForecast {date: string;temperatureC: number;temperatureF: number;summary: string;}

You can checkout this project example on GitHub,

Thank You, See you in the next article !!

You can reach out or connect to me over here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *