our

Latest Blogs

Authentication with JSON Web Token in Angular

iFour Team -June 30, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  •  
  •  
  •  
Authentication with JSON Web Token in Angular

Why we use JSON Web Token?

JSON Web Token is the best way of transmitting information between two parties securely because here the user identity is strictly verified. When the user logs in with true credentials, then a specific ID token gets generated and returned.

Example of json web token authentication in angular

auth.guard.ts File at the Front-end side

In this class we implement guard to decide if the route is active or not. If the guard returns true it navigates and if the guard returns false, then it cancels the navigation.

Auth guard is used to check if the user is logged in or not. If the user is logged in, it returns true from canActivate() method otherwise it returns false and redirects to the login page.

 

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (localStorage.getItem('token') != null)
return true;
else {
this.router.navigate(['/user/login']);
return false;
}
}
}

 

 

auth.interceptor.ts File at Front-end side

 

The interceptor file is intercepted HTTP responses from API and check there are any errors. If users are unauthorized then it will return a 401 status code error. HTTP Interceptor class is included in the HttpClientModule.

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { Router } from "@angular/router";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
if (localStorage.getItem('token') != null) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
});
return next.handle(clonedReq).pipe(
tap(
succ => { },
err => {
if (err.status == 401){
localStorage.removeItem('token');
this.router.navigateByUrl('/user/login');
}
}
)
)
}
else
return next.handle(req.clone());
}
}

 

User.service.ts file to use back-end API

 

This file is used to call the back-end API. And I use ASP.Net Core in back-end.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { FormBuilder, Validators, FormGroup ,AbstractControl, FormControl} from '@angular/forms';

@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private fb: FormBuilder, private http: HttpClient) { }
readonly rootURL ="http://localhost:55581/api"
formModel = this.fb.group({
UserName: ['', Validators.required],
Email: ['', Validators.email],
FullName: [''],
Passwords: this.fb.group({
Password: ['', [Validators.required, Validators.minLength(4)]],
ConfirmPassword: ['', Validators.required]
}, { validator: this.comparePasswords })
});
comparePasswords(fb: FormGroup) {
let confirmPswrd = fb.get('ConfirmPassword') as FormControl;
//passwordMismatch
//confirmPswrdCtrl.errors={passwordMismatch:true}
if (confirmPswrd.errors == null || 'passwordMismtch' in confirmPswrd.errors) {
if (fb.get('Password')!.value != confirmPswrd.value)
{ confirmPswrd.setErrors({ passwordMismtch: true });}
else
{
confirmPswrd.setErrors(null);}
}
}
register() {
var body = {
UserName: this.formModel.value.UserName,
Email: this.formModel.value.Email,
FullName: this.formModel.value.FullName,
Password: this.formModel.value.Passwords.Password
}; 
return this.http.post("https://localhost:44318/api/ApplicationUser/Register", body);
}
login(UserData: any) {
debugger;
return this.http.post("https://localhost:44318/api/ApplicationUser/Login", UserData);
}
}

 

Home.component.html file

 

This file contains an HTML template and angular 11 template syntax for displaying a simple welcome page with user detail.

Home-Component-Html

 

Home.component.ts file

 

This component gets the user detail from the user service and makes them available to the template.

import { UserService } from './../shared/user.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styles: []
})
export class HomeComponent implements OnInit {
  userDetails;
  constructor(private router: Router, private service: UserService) { }
  ngOnInit() {
    this.service.getUserProfile().subscribe(
      res => {
        this.userDetails = res;
      },
      err => {
        console.log(err);
      },
    );
  }
  onLogout() {
    localStorage.removeItem('token');
    this.router.navigate(['/user/login']);
  }
}

 

Login.component.html file

 

This template contains a login form with a username and password field. And it displays a validation message for invalid fields when the submit button is clicked. The form that submits the event is to the onSubmit() method of login component.

Login-Component-Html

 

Login.component.ts file

 

This component is using the authentication service to log in to the application. If users are already logged in they are automatically redirected to the home page.

 

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/shared/user.service';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
formModel = {
UserName: '',
Password: ''
}
constructor(private service: UserService, private router: Router, private toastrrr: ToastrService) { }
ngOnInit() {
if (localStorage.getItem('token') != null)
this.router.navigateByUrl('/home');
}
onSubmit(form: NgForm) {
this.service.login(form.value).subscribe(
(res: any) => {
localStorage.setItem('token', res.token);
this.router.navigateByUrl('/home');
},
err => {
if (err.status == 400)
this.toastrrr.error('Incorrect username or password.', 'Authentication failed.');
else
console.log(err);
}
);
}
}

 

 

Registration.component.html file

 

This component template contains a registration form with many fields.

Registration-Component-Html

One-stop-oplossing voor Angular-webontwikkeling - Uw zoekopdracht eindigt hier.

 

Registration.component.ts file

 

This component is using the registration service to register the user details.

import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { UserService } from 'src/app/shared/user.service';

@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
constructor(public service: UserService, private toastrr: ToastrService) { }
ngOnInit() {
this.service.formModel.reset();
}
onSubmit() {
this.service.register().subscribe(
(res: any) => {
if (res.succeeded) {
this.service.formModel.reset();
this.toastrr.success('New user created!', 'Registration successful.');
} else {
res.errors.forEach((element: any ) => {
switch (element.code) {
case 'DuplicateUserName':
this.toastrr.error('Username is already taken','Registration failed.');
break;
default:
this.toastrr.error(element.description,'Registration failed.');
break;
}
});
}
},
err => {
console.log(err);
}
);
}
}

 

User component template

 

User-Component-Html

 

App-routing.module.ts file

 

In this component, we routing our application.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserComponent } from './user/user.component';
import { RegistrationComponent } from './user/registration/registration.component';
import { LoginComponent } from './user/login/login.component';
import { HomeComponent } from './home/home.component';
import { AuthGuard } from './auth/auth.guard';

const routes: Routes = [
{path:'',redirectTo:'/user/login',pathMatch:'full'},
{
path: 'user', component: UserComponent,
children: [
{ path: 'registration', component: RegistrationComponent },
{ path: 'login', component: LoginComponent }
]
},
{path:'home',component:HomeComponent,canActivate:[AuthGuard]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

 

app.module.ts file

 

You need to import a module that you have to use in your application.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NgxPaginationModule} from 'ngx-pagination';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { LoginComponent } from './user/login/login.component';
import { RegistrationComponent } from './user/registration/registration.component';
import { HomeComponent } from './home/home.component';
import{UserService} from './shared/user.service';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from './auth/auth.interceptor';
import { AuthGuard } from './auth/auth.guard';

export function tokenGetter() {
return localStorage.getItem("jwt");
}
@NgModule({
declarations: [
AppComponent,
UserComponent,
LoginComponent,
RegistrationComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,FormsModule,ReactiveFormsModule,ToastrModule.forRoot({
progressBar: true
}),BrowserAnimationsModule,HttpClientModule,NgxPaginationModule
],
providers: [UserService,{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true},AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Conclusion

In this blog, we have seen what is JSON Web Token Authentication in Angular and how to use JSON Web Token. Using JSON Web Token in Your Angular application can verify with a back-end that produces a JSON web token and angular application can then pass that token in an authorization header to the back-end and the back-end proved they are authenticated and the back-end is verifying the JSON web token and grant to access system.

Work with us

Well do everything we can to make our next best project!

Our Insights

Check out our most recent blogs

An in-depth guide on Angular Dependency Providers
An in-depth guide on Angular Dependency Providers

What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...

A simple guide on AOT Compilation in Angular
A simple guide on AOT Compilation in Angular

What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...

A simple guide on NgRx Entity in Angular
A simple guide on NgRx Entity in Angular

Introduction Angular is a remarkable framework that may be used to create mobile and desktop web apps with spectacular UIs. It's made with JavaScript. we can utilize HTML, CSS,...

Our Partners

Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo

Work With Us

Well do everything we can to make our next best project!