
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
angular2-jwt
Advanced tools
angular2-jwt is a helper library for working with JWTs in your Angular 2 applications.
AuthHttp
classnpm install
The library comes with several helpers that are useful in your Angular 2 apps.
AuthHttp
- allows for individual and explicit authenticated HTTP requestsAuthStatus
- 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 requests, you can use the AuthHttp
class.
// app.ts
import {Component, View, bootstrap, provide} from 'angular2/angular2';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {AuthHttp} from 'angular2-jwt/angular2-jwt';
...
class App {
thing: string;
constructor(public authHttp:AuthHttp) {}
getThing() {
this.authHttp.get('http://example.com/api/thing')
.map(res => res.json())
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
}
}
bootstrap(App, [
HTTP_PROVIDERS,
provide(AuthHttp, { useFactory: () => {
return new AuthHttp()
}})
])
A default configuration for header and token details is provided:
Authorization
Bearer
id_token
(() => localStorage.getItem(tokenName))
true
If you wish to configure the headerName
, headerPrefix
, tokenName
, tokenGetter
function, or noJwtError
boolean, you can pass a config object when AuthHttp
is injected.
By default, if there is no valid JWT saved, AuthHttp
will throw an 'Invalid JWT' error. If you would like to continue with an unauthenticated request instead, you can set noJwtError
to true
.
// app.ts
...
bootstrap(App, [
HTTP_PROVIDERS,
provide(AuthHttp, { useFactory: () => {
return new AuthHttp({
headerName: YOUR_HEADER_NAME,
headerPrefix: YOUR_HEADER_PREFIX,
tokenName: YOUR_TOKEN_NAME,
tokenGetter: YOUR_TOKEN_GETTER_FUNCTION,
noJwtError: true
})
}})
])
The AuthHttp
class supports all the same HTTP verbs as Angular 2's Http.
If you wish to use the JWT as an observable stream, you can call tokenStream
from AuthHttp
.
// app.ts
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.
// app.ts
...
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
.
The router's @CanActivate
lifecycle hook can be used with tokenNotExpired
to determine if a route should be accessible. This lifecycle hook is run before the component class instantiates. If @CanActivate
receives true
, the router will allow navigation, and if it receives false
, it won't.
// app.ts
...
import {Component, View, bootstrap, provide} from 'angular2/http';
import {tokenNotExpired} from 'angular2-jwt/angular2-jwt';
import {RouteConfig, RouteParams, ROUTER_DIRECTIVES, APP_BASE_HREF, ROUTER_PROVIDERS, CanActivate} from 'angular2/router'
@Component({
selector: 'secret-route'
})
@View({
template: `<h1>If you see this, you have a JWT</h1>`
})
@CanActivate(() => tokenNotExpired())
class SecretRoute {}
You can pass a different tokenName
for @CanActivate
to use as the first argument to the function. If you wish to define your own function for tokenNotExpired
to use, pass null
first and then the function.
To extend or contribute to this library, first clone the repo. A gulp task is set up for transpiling the TypeScript file to ES5. Just run gulp
and changes will be watched.
Auth0 helps you to:
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 angular2-jwt receives a total of 2,716 weekly downloads. As such, angular2-jwt popularity was classified as popular.
We found that 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
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.