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

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 - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.