python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 4

Angular 5 JWT Login Authentication Examples Step by Step

What Is JWT? 
The JWT is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

How to setup a simple login page using Angular 5 and JWT authentication?
In Annular 5, the following steps are used to building authentication and authorization for RESTful APIs and applications. I hope it might help you all-
1.        The users send their credentials to the server which is verified by the database credentials. If everything is verified successfully, the JWT is sent back to them.
2.        The JWT is saved in the user's browser in local storage or in a cookie and so on.
3.        The presence of a JWT saved in the browser is used as an indicator that a user is currently logged in.
4.        The expiry time of JWT is continually checked to maintain an authenticated state in the Angular applications.
5.        The client side routes are protected and access by authenticated users only.
6.        When user sends the XHR requests for APIs, the JWT gets sent an Authorization header using your cookies or Bearer.
7.        When XHR requests coming on the server, before send back the responses it’s validated first with configured app's secret keys. If everything is looking good then returns successfully responses other send the back to the bad request.

There are several open source libraries are available for angular which are helps with JWTs and has the ability to Decode the JWT, Authorization header to XHR requests and so on.

JWT Authorization service integration in Angular 5 is used to secure login and logout of the application. Firstly we need to make a POST request for login with username and password.

Let’s start the example steps by steps.

Angular 5 User Model – I have created the user class using the CLI commands and write the User property (as per your requirement).

ng g class User

Example for User model –
export class User {
    username: string;
    password: string;
    firstName: string;
    lastName: string;

Also added a constant class for global variable and it looks like –
export class AppConstants {
    public static get baseURL(): string { return "http://localhost:4200/api"; }

Angular 5 JWT Authentication Service - I have created the Authentication Service using the CLI command -
ng g service Authentication

Example – authentication.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";
import { Observable } from 'rxjs';
import{ AppConstants} from '../app/constants'

export class AuthenticationService {
 //variable initialization
 _token : any;
 _baseURL : string;

 //constructor initialization
  constructor(private _htc:HttpClient) {
     //set token if saved in local storage
     var currentUser = JSON.parse(localStorage.getItem('currentUser'));
     this._token = currentUser && currentUser.token;
     this._baseURL = AppConstants.baseURL;

   login(username: string, password: string): Observable<boolean> {
    return +'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successfully, if there is a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                //set the token property for validate token in the app.
                this._token = token;

                //store username and jwt token in local storage to keep user logged in between page refreshes.
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                //returns true to indicate successful login
                return true;
            else {
                // returns false to indicate failed login
                return false;

logout(): void {
    // clear token remove user from local storage to log user out.
    this._token = null;

Angular 5 User Service – I have created the User Service using the CLI command –
ng g service User

Example – user.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";
import { Observable } from 'rxjs';

import {AuthenticationService} from './authentication.service';
import {User} from './user'
import{ AppConstants} from '../app/constants'

export class UserService {

 //variable initialization
 _baseURL : string;

 //Immutable set of Http headers, with lazy parsing.
 private _headers = new HttpHeaders().set('Content-Type', 'application/json');

 //constructor initialization
  constructor(private _htc:HttpClient, private authService: AuthenticationService) {
    this._baseURL = AppConstants.baseURL;

   //Get Users Detail.
   getUsers(): Observable<User[]> {
    const headers = this._headers.append('Authorization:', 'Bearer ' + this.authService._token);

    //Get users from REST API
    return this._htc.get<User[]>(this._baseURL, { headers : headers });

Angular 5 User Component - I have created the User Component using the CLI command –
ng g component User

Example - user.component.ts
<div class="col-md-6 col-md-offset-3">
  <h1>User</h1><p><a [routerLink]="['/login']">Logout</a></p>
      <h3>User List from secure APIs end point -</h3>
          <div *ngFor="let user of userList">{{user.firstName}} {{user.lastName}}</div>

Angular 5 Login Component – login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthenticationService } from '../authentication.service';

  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
export class LoginComponent implements OnInit {
  //variable initialization
  model: any ={};
  public errorMsg = '';

  //constructor initialization
  constructor(private _fbuilder: FormBuilder,
    private route: Router,
    private _authService: AuthenticationService) {
      this.loginForm ={
        username: ['', [Validators.required,]],
        password: ['', Validators.required, Validators.minLength(6)]

  //ngOnInit method for load data.
  ngOnInit() {
    //clear everything using logout.

  //This method use for Login
  login(user) {
    if (this.loginForm.valid) {
      if(this.loginForm.username !== undefined && this.loginForm.username !== null &&
        this.loginForm.password !== undefined && this.loginForm.password !== null){
          //Call Login service for validate username and password.
          this._authService.login(this.loginForm.username, this.loginForm.password)
            .subscribe(result => {
              if (result === true) {
                  // login successful
              } else {
                  // login failed
                  this.errorMsg = 'Username or password is incorrect.';
      this.errorMsg = 'login failed, Please try again!';

Angular 5 App Module and App Routing - The app module defines the root module of the application along with metadata about the module.
Example –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule, FormGroup} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {HttpClientModule} from "@angular/common/http";
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
// import { RegisterComponent } from './register/register.component';
// import { EmployeeComponent } from './employee/employee.component';
import { UserComponent } from './user/user.component';

//My Services
import { AuthServiceService } from './auth-service.service';
import { AuthGuard } from './auth.guard';
import { EmployeeService} from './employee.service';
import { ValidationService } from './validation.service';
import {AuthenticationService} from './authentication.service';
import {UserService} from './user.service';

  declarations: [
    // RegisterComponent,
    // EmployeeComponent,
  imports: [
      { path: '', component: AppComponent, pathMatch: 'full' },
      { path: 'user', component: UserComponent},
      { path: 'login', component: LoginComponent}])
  providers: [EmployeeService, ValidationService,
          AuthenticationService, UserService],
  bootstrap: [AppComponent]
export class AppModule { }

The login page request looks like –
I hope you are enjoying with this post! Please share with you friends! Thank you!!

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions