Angular 5 JWT Login Authentication Examples Step by Step - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Angular 5 JWT Login Authentication Examples Step by Step

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-
  •  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.
  •  The JWT is saved in the user's browser in local storage or in a cookie and so on.
  •  The presence of a JWT saved in the browser is used as an indicator that a user is currently logged in.
  •  The expiry time of JWT is continually checked to maintain an authenticated state in the Angular applications.
  •  The client side routes are protected and access by authenticated users only.
  •  When user sends the XHR requests for APIs, the JWT gets sent an Authorization header using your cookies or Bearer.
  •  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 {
    usernamestring;
    passwordstring;
    firstNamestring;
    lastNamestring;
}

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 {HttpClientHttpParamsHttpHeadersfrom "@angular/common/http";
import { Observable } from 'rxjs';
importAppConstantsfrom '../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(usernamestringpasswordstring): Observable<boolean> {
    return this._htc.post(this._baseURL +'/authenticate'JSON.stringify({ username: usernamepassword: password }))
        .map((responseResponse=> {
            // 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: usernametoken: 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 {HttpClientHttpParamsHttpHeadersfrom "@angular/common/http";
import { Observable } from 'rxjs';

import {AuthenticationServicefrom './authentication.service';
import {Userfrom './user'
importAppConstantsfrom '../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:HttpClientprivate authServiceAuthenticationService) {
    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 { ComponentOnInit } from '@angular/core';
import { FormBuilderValidators } 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;
  modelany ={};
  public errorMsg = '';

  //constructor initialization
  constructor(private _fbuilderFormBuilder,
    private routeRouter,
    private _authServiceAuthenticationService) {
      this.loginForm = _fbuilder.group({
        username: ['', [Validators.requiredValidators.email]],
        password: [''Validators.requiredValidators.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.usernamethis.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 {FormsModuleFormGroupfrom '@angular/forms';
import {RouterModulefrom '@angular/router';
import {HttpClientModulefrom "@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 { EmployeeServicefrom './employee.service';
import { ValidationService } from './validation.service';
import {AuthenticationServicefrom './authentication.service';
import {UserServicefrom './user.service';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    // RegisterComponent,
    // EmployeeComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot([
      path: ''component: AppComponentpathMatch: 'full' },
      path: 'user'component: UserComponent},
      path: 'login'component: LoginComponent}])
  ],
  providers: [EmployeeServiceValidationService,
          AuthenticationServiceUserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.