JWT Authentication & Authorization With .NET Core & Angular

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² *

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Trustless Authentication system with NodeJS and Nu.Id

Changing the Handlebars extension and adding complete code to a view Express.js Handlebars

8 Tips Programmers Can Do to Solve Bugs and Problems in Production

14 Frequently Asked Questions about ReactJS

Some CSS Pointers

Stacks and Queues in JavaScript

Let is the new Var

JavaScript Build Tools and Automation Systems

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vaibhav Bhapkar

Vaibhav Bhapkar

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

More from Medium

Azure AD Authentication Implementation in Angular

Develop an Online Shop with Angular 11 and .Net Core 5

Creating and Build a Desktop Application with Angular and Electron

🔑Auth0 in Angular : [Part1]Authenticate your Angular app