Name: angular2-jwt
Owner: Auth0
Description: Helper library for handling JWTs in Angular 2 apps
Created: 2015-10-26 05:37:39.0
Updated: 2018-01-17 22:03:58.0
Pushed: 2018-01-17 21:49:57.0
Homepage: null
Size: 198
Language: TypeScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
angular2-jwt is a helper library for working with JWTs in your Angular 2 applications.
HttpInterceptor
support, see the v1.0 branch.For examples of integrating angular2-jwt with SystemJS, see auth0-angular2.
angular2-jwt is a small and unopinionated library that is useful for automatically attaching a JSON Web Token (JWT) as an Authorization
header when making HTTP requests from an Angular 2 app. It also has a number of helper methods that are useful for doing things like decoding JWTs.
This library does not have any functionality for (or opinion about) implementing user authentication and retrieving JWTs to begin with. Those details will vary depending on your setup, but in most cases, you will use a regular HTTP request to authenticate your users and then save their JWTs in local storage or in a cookie if successful.
For more on implementing authentication endpoints, see this tutorial for an example using HapiJS.
AuthHttp
classinstall angular2-jwt
The library comes with several helpers that are useful in your Angular 2 apps.
AuthHttp
- allows for individual and explicit authenticated HTTP requeststokenNotExpired
- allows you to check whether there is a non-expired JWT in local storage. This can be used for conditionally showing/hiding elements and stopping navigation to certain routes if the user isn't authenticatedCreate a new auth.module.ts
file with the following code:
rt { NgModule } from '@angular/core';
rt { Http, RequestOptions } from '@angular/http';
rt { AuthHttp, AuthConfig } from 'angular2-jwt';
rt function authHttpServiceFactory(http: Http, options: RequestOptions) {
turn new AuthHttp(new AuthConfig(), http, options);
odule({
oviders: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
rt class AuthModule {}
We added a factory function to use as a provider for AuthHttp
. This will allow you to configure angular2-jwt in the AuthConfig
instance later on.
If you wish to only send a JWT on a specific HTTP request, you can use the AuthHttp
class. This class is a wrapper for Angular 2's Http
and thus supports all the same HTTP methods.
rt { AuthHttp } from 'angular2-jwt';
..
s App {
ing: string;
nstructor(public authHttp: AuthHttp) {}
tThing() {
this.authHttp.get('http://example.com/api/thing')
.subscribe(
data => this.thing = data,
err => console.log(err),
() => console.log('Request Complete')
);
AUTH_PROVIDERS
gives a default configuration setup:
Authorization
Bearer
token
(() => localStorage.getItem(tokenName))
false
If you wish to configure the headerName
, headerPrefix
, tokenName
, tokenGetter
function, noTokenScheme
, globalHeaders
, or noJwtError
boolean, you can using provideAuth
or the factory pattern (see below).
By default, if there is no valid JWT saved, AuthHttp
will return an Observable error
with 'Invalid JWT'. If you would like to continue with an unauthenticated request instead, you can set noJwtError
to true
.
The default scheme for the Authorization
header is Bearer
, but you may either provide your own by specifying a headerPrefix
, or you may remove the prefix altogether by setting noTokenScheme
to true
.
You may set as many global headers as you like by passing an array of header-shaped objects to globalHeaders
.
You may customize any of the above options using a factory which returns an AuthHttp
instance with the options you would like to change.
rt { NgModule } from '@angular/core';
rt { Http, RequestOptions } from '@angular/http';
rt { AuthHttp, AuthConfig } from 'angular2-jwt';
rt function authHttpServiceFactory(http: Http, options: RequestOptions) {
turn new AuthHttp(new AuthConfig({
tokenName: 'token',
tokenGetter: (() => sessionStorage.getItem('token')),
globalHeaders: [{'Content-Type':'application/json'}],
}), http, options);
odule({
oviders: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
rt class AuthModule {}
To configure angular2-jwt in Ionic 2 applications, use the factory pattern in your @NgModule
. Since Ionic 2 provides its own API for accessing local storage, configure the tokenGetter
to use it.
rt { AuthHttp, AuthConfig } from 'angular2-jwt';
rt { Http } from '@angular/http';
rt { Storage } from '@ionic/storage';
storage = new Storage({});
rt function getAuthHttp(http) {
turn new AuthHttp(new AuthConfig({
headerPrefix: YOUR_HEADER_PREFIX,
noJwtError: true,
globalHeaders: [{'Accept': 'application/json'}],
tokenGetter: (() => storage.get('token').then((token: string) => token)),
, http);
odule({
ports: [
IonicModule.forRoot(MyApp),
oviders: [
{
provide: AuthHttp,
useFactory: getAuthHttp,
deps: [Http]
},
...
otstrap: [IonicApp],
...
You may also send custom headers on a per-request basis with your authHttp
request by passing them in an options object.
hing() {
t myHeader = new Headers();
Header.append('Content-Type', 'application/json');
is.authHttp.get('http://example.com/api/thing', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
Pass it after the body in a POST request
is.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(err),
() => console.log('Request Complete')
);
If you wish to use the JWT as an observable stream, you can call tokenStream
from AuthHttp
.
nSubscription() {
is.authHttp.tokenStream.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('Complete')
);
This can be useful for cases where you want to make HTTP requests out of observable streams. The tokenStream
can be mapped and combined with other streams at will.
The JwtHelper
class has several useful methods that can be utilized in your components:
decodeToken
getTokenExpirationDate
isTokenExpired
You can use these methods by passing in the token to be evaluated.
elper: JwtHelper = new JwtHelper();
wtHelper() {
r token = localStorage.getItem('token');
nsole.log(
this.jwtHelper.decodeToken(token),
this.jwtHelper.getTokenExpirationDate(token),
this.jwtHelper.isTokenExpired(token)
The tokenNotExpired
function can be used to check whether a JWT exists in local storage, and if it does, whether it has expired or not. If the token is valid, tokenNotExpired
returns true
, otherwise it returns false
.
Note:
tokenNotExpired
will by default assume the token name istoken
unless a token name is passed to it, ex:tokenNotExpired('token_name')
. This will be changed in a future release to automatically use the token name that is set inAuthConfig
.
uth.service.ts
rt { tokenNotExpired } from 'angular2-jwt';
edIn() {
turn tokenNotExpired();
The loggedIn
method can now be used in views to conditionally hide and show elements.
tton id="login" *ngIf="!auth.loggedIn()">Log In</button>
tton id="logout" *ngIf="auth.loggedIn()">Log Out</button>
To guard routes that should be limited to authenticated users, set up an AuthGuard
.
uth-guard.service.ts
rt { Injectable } from '@angular/core';
rt { Router } from '@angular/router';
rt { CanActivate } from '@angular/router';
rt { Auth } from './auth.service';
ectable()
rt class AuthGuard implements CanActivate {
nstructor(private auth: Auth, private router: Router) {}
nActivate() {
if(this.auth.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
With the guard in place, you can use it in your route configuration.
rt { AuthGuard } from './auth.guard';
rt const routes: RouterConfig = [
path: 'admin', component: AdminComponent, canActivate: [AuthGuard] },
path: 'unauthorized', component: UnauthorizedComponent }
Pull requests are welcome!
Use npm run dev
to compile and watch for changes.
Auth0 helps you to:
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.