angular2-jsonwebtoken
v0.8.1
Published
Http Helper library for managing JWT-based authentication in angular2 apps
Downloads
70
Maintainers
Readme
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
- Once installed you need to import the module:
import {Angular2JWTModule} from 'angular2-jsonwebtoken';
- Declare it in the imports section of your module:
@NgModule({
declarations: [AppComponent, ...],
imports: [Angular2JWTModule, ...], //import the Angular2JWTModule
bootstrap: [AppComponent]
})
export class AppModule {
}
- 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
],
...
})