![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
@zoitravel/angular2-jwt
Advanced tools
angular2-jwt is a helper library for working with JWTs in your Angular 2 applications.
For examples on integrating angular2-jwt with Webpack and 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 or opinion about how you should be 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
classnpm install 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 authenticatedIf you wish to only send a JWT on a specific HTTP request, you can use the AuthHttp
class.
import { AuthHttp, AuthConfig, AUTH_PROVIDERS } from 'angular2-jwt';
...
class App {
thing: string;
constructor(public authHttp: AuthHttp) {}
getThing() {
this.authHttp.get('http://example.com/api/thing')
.subscribe(
data => this.thing = data,
err => console.log(err),
() => console.log('Request Complete')
);
}
}
bootstrap(App, [
HTTP_PROVIDERS,
AUTH_PROVIDERS
])
AUTH_PROVIDERS
gives a default configuration setup:
Authorization
Bearer
id_token
(() => localStorage.getItem(tokenName))
false
If you wish to configure the headerName
, headerPrefix
, tokenName
, tokenGetter
function, noTokenScheme
, globalHeaders
, or noJwtError
boolean, you can pass a config object when AuthHttp
is injected.
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
.
import { provideAuth } from 'angular2-jwt';
...
bootstrap(App, [
HTTP_PROVIDERS,
provideAuth({
headerName: YOUR_HEADER_NAME,
headerPrefix: YOUR_HEADER_PREFIX,
tokenName: YOUR_TOKEN_NAME,
tokenGetter: YOUR_TOKEN_GETTER_FUNCTION,
globalHeaders: [{'Content-Type':'application/json'}],
noJwtError: true,
noTokenScheme: true
})
])
The AuthHttp
class supports all the same HTTP verbs as Angular 2's Http.
You may also send custom headers on a per-request basis with your authHttp
request by passing them in an options object.
getThing() {
let myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
this.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
this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
}
If you wish to use the JWT as an observable stream, you can call tokenStream
from AuthHttp
.
...
tokenSubscription() {
this.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 obsevable 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.
...
jwtHelper: JwtHelper = new JwtHelper();
...
useJwtHelper() {
var token = localStorage.getItem('id_token');
console.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 isid_token
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
.
// auth.service.ts
import { tokenNotExpired } from 'angular2-jwt';
...
loggedIn() {
return tokenNotExpired();
}
...
The loggedIn
method can now be used in views to conditionally hide and show elements.
<button id="login" *ngIf="!auth.loggedIn()">Log In</button>
<button id="logout" *ngIf="auth.loggedIn()">Log Out</button>
To guard routes that should be limited to authenticated users, set up an AuthGuard
.
// auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { Auth } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: Auth, private router: Router) {}
canActivate() {
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.
...
import { AuthGuard } from './auth.guard';
export 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.
FAQs
Helper library for handling JWTs in Angular 2
The npm package @zoitravel/angular2-jwt receives a total of 2 weekly downloads. As such, @zoitravel/angular2-jwt popularity was classified as not popular.
We found that @zoitravel/angular2-jwt demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.