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 2 Authentications with Angular2-JWT

Angular 2 Authentications with Angular2-JWT

What is JWT?
JWT is Stand for “JSON Web Token”. It is stateless Authentication in Angular Apps and Easily Angular apps are authenticated with JWT!


JWT Contain Three Parts -
1.     Header – Is used to define the algorithm to sign the token and token type.
2.     Payload – It is used to keep a JSON object of all the claims which you want.
3.     Signature - It is secret key and used to verify the Signature!

JWT Key Features -
1.     Decode a JWT from your Angular app and read its payload
2.     Attach the JWT as an Authorization header to XHR requests
3.     Existing service method (logging in and logging out) are used to checks whether the current user's JWT is expired or not.

JWT Installation from NPM -
> npm install angular2-jwt

Application Module Configuration -
import { NgModule } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig(), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ]
})
export class AuthModule {}

AUTH_PROVIDERS default Configuration Options-
1.     Header Name: Authorization
2.     Header Prefix: Bearer
3.     Token Name: token
4.     Token Getter Function: (() => localStorage.getItem(tokenName))
5.     Supress error and continue with regular HTTP request if no JWT is saved: false
6.     Global Headers: none

Advanced Configuration -
1.     AuthHttp - allows us to authenticated HTTP requests
2.     tokenNotExpired - allows us to check expired or not JWT in local storage.

Example As -
import { NgModule } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
      tokenName: 'token', tokenGetter: (() => sessionStorage.getItem('token')),
  globalHeaders: [{'Content-Type':'application/json'}],
 }), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ]
})
export class AuthModule {}

How to set Per-Request Headers? How to Call Authenticated Requests?

Example As –
import { AuthHttp } from 'angular2-jwt';

class App {
  yourthing: string;

  constructor(public authHttp: AuthHttp) {}

  getThing() {
    let header = new Headers();
    header.append('Content-Type', 'application/json');

    this.authHttp.get('~/api/yourthing', { headers: header })
      .subscribe( data => this.thing = data, err => console.log(err),
         () => console.log('Request Complete')
      );
  }
}

References –

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions