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

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 ...

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin...

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...

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan ...

55 Best TypeScript Interview Questions and Answers - JavaScript!

What Is TypeScript? By definition, "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." TypeScript is a superset of JavaScript which provides optional static typing, classes and interfaces. => The TypeScript was first made public in the year 2012. => Typescript is a modern age JavaScript development language. => TypeScript is a strongly typed, object oriented, compiled language. => TypeScript was designed by Anders Hejlsberg (designer of C#) at Microsoft. => TypeScript is both a language and a set of tools. As an Example of TypeScript, class Hello {     msg : string ;      constructor ( message : string ) {          this . msg = message ;      }       getMsg () {          return "Hello, " + this . msg ;      } } TypeScript introduced a great deal...