Skip to main content

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'

@Injectable()
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 this._htc.post(this._baseURL +'/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;
    localStorage.removeItem('currentUser');
  }
}


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'

@Injectable()
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>
  <div>
      <h3>User List from secure APIs end point -</h3>
      <div>
          <div *ngFor="let user of userList">{{user.firstName}} {{user.lastName}}</div>
      </div>
  </div>
</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';

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

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

  //ngOnInit method for load data.
  ngOnInit() {
    //clear everything using logout.
    this._authService.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
                  this.route.navigate(["user"]);
              } else {
                  // login failed
                  this.errorMsg = 'Username or password is incorrect.';
              }
          });         
      }
    }
    else{
      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";
//MY COMPONENTS
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';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    // RegisterComponent,
    // EmployeeComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot([
      { 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!!
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVA...

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from ...

React Lifecycle Components | Mounting, Updating, Unmounting

In React, each component has a life-cycle which manipulate during its three main phases. The following three phases are: 1.       Mounting 2.       Updating 3.       Unmounting React does so by “ Mounting ” (adding nodes to the DOM), “ Unmounting ” (removing them from the DOM), and “ Updating ” (making changes to nodes already in the DOM). Mounting - Lifecycle Phase 1 Mounting is used for adding nodes (elements) to the DOM. The React has four built-in methods that gets called, in this order, when mounting a component - 1.       constructor() 2.       getDerivedStateFromProps() 3.       render() 4.       componentDidMount() Note – 1)       The render() method is required and It always be called and the others methods are optional (you will call...

51 Best React Interview Questions and Answers

1) What Is React? React is a fast, open-source, and front-end JavaScript library and It was developed by Facebook in 2011 for building complex, stateful and interactive UI in web as well as mobile Applications. React follows the component based approach which helps you to building reusable and interactive web and mobile user interface (UI) components. React has one of the largest communities supporting it. The high level component Lifecycle - At the highest level component Lifecycle, React components have lifecycle events that are - 1.       Initialization 2.       State/Property Updates 3.       Destruction Explore to detail understanding   -  React Lifecycle Components Reactjs is very fast technology that can be trusted for complex tasks and can simply be trusted for quality outcomes. 2) When Reactjs released? March 2013 3) What Is the current stable version of ...

39 Best Yii2 Interview Questions and Answers - PHP Frameworks

1: What Is Yii framework? 2: Why Yii Is So Fast? 3: Yii Versions? 4: What Are the Prerequisites Yii? 5: Why Use Yii 2.0 Framework? 6: What Are the Benefits of Yii over other Frameworks? 7: What's New in Yii Release 2.0? 8: What Is The First File That Gets Loaded When You Run A Application Using Yii? 9: What Is The First Function That Gets Loaded From A Controller? 10: What Are the core components of Yii2 framework? 11: What Are the great feature of Yii Framework? 12: What Are The Application Structure of Yii 2.0 Framework? 13: What Are the Naming Convention in Yii 2.0 Framework? 14: What Is Request Life-Cycle of Yii 2.0 framework? 15: What Are Yii helpers? 16: What Are the Core Helper Classes in Yii Framework? 17: What Are The Server Requirements to Install Yii 2.0 Framework? 18: How To Customizing Helper Classes in Yii Framework? 19: What Are The Directory Structure of Yii 2.0 Framework? 20: How To Create Directory Structure of Yii Framewor...