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.

Project Structure
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);}}
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’);}}
<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>
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.”}});}}
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;}

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