angular2-jsonwebtoken
TypeScript icon, indicating that this package has built-in type declarations

0.8.1 • Public • Published

angular2-jsonwebtoken

Http Helper library for managing JWT-based authentication in angular2 apps

What is This Library For?

angular2-jsonwebtoken is a library used for authentication via JSON Web Token in Angular 2 applications, which adds to the HTTP requests a header with "Authorization: Bearer your-web-token".

How to use it?

Instalation

npm install --save angular2-jsonwebtoken.

Usage

  1. Once installed you need to import the module:
import {Angular2JWTModule} from 'angular2-jsonwebtoken';
  1. Declare it in the imports section of your module:
@NgModule({
  declarations: [AppComponent, ...],
  imports: [Angular2JWTModule, ...], //import the Angular2JWTModule
  bootstrap: [AppComponent]
})
export class AppModule {
}
  1. Make authenticated HTTP requests:
import { AuthHttp, AuthConfig} from 'angular2-jsonwebtoken';

...

class App {

// inject the AuthHttp in the 
  constructor(public authHttp: AuthHttp) {}

  doSomething() {
    this.authHttp.get('/route')
      .subscribe(
        data => console.log(data),
        err => console.log(err),
        () => console.log('RequestComplete')
      );
  }
}

Configuration

By default, the token is stored in the local storage, using the key "auth_token". If you need to change it, you can use your own configuration:

@NgModule({
    imports: [
        AppModule,
        ...
    ],
    providers: [
        ...,
        {
            provide: AuthConfig,
            useFactory: () => {
                return new AuthConfig({
                    headerName: 'Authorization',
                    headerPrefix: 'Bearer ',
                    tokenName: 'auth_token',
                    tokenGetter: (() => localStorage.getItem(this.tokenName)),
                    noJwtError: false;
                });
            },
            deps: [Http]
        },
        AuthHttp
    ],
    ...
})

Package Sidebar

Install

npm i angular2-jsonwebtoken

Weekly Downloads

14

Version

0.8.1

License

MIT

Last publish

Collaborators

  • avhincu