What is @auth0/angular-jwt?
@auth0/angular-jwt is an Angular library that provides utilities for handling JSON Web Tokens (JWT). It helps in managing token-based authentication in Angular applications by providing features such as token decoding, token expiration checking, and HTTP request interception to automatically add JWTs to requests.
What are @auth0/angular-jwt's main functionalities?
Token Decoding
This feature allows you to decode a JWT to access its payload. The JwtHelperService provides a method decodeToken that takes a raw JWT string and returns its decoded payload.
import { JwtHelperService } from '@auth0/angular-jwt';
const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(myRawToken);
console.log(decodedToken);
Token Expiration Checking
This feature allows you to check if a JWT has expired. The JwtHelperService provides a method isTokenExpired that takes a raw JWT string and returns a boolean indicating whether the token is expired.
import { JwtHelperService } from '@auth0/angular-jwt';
const helper = new JwtHelperService();
const isExpired = helper.isTokenExpired(myRawToken);
console.log(isExpired);
HTTP Request Interception
This feature allows you to automatically add JWTs to HTTP requests. By configuring the JwtModule and providing a tokenGetter function, you can intercept HTTP requests and add the JWT to the Authorization header.
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
export function tokenGetter() {
return localStorage.getItem('access_token');
}
@NgModule({
imports: [
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ['example.com'],
disallowedRoutes: ['example.com/examplebadroute/'],
},
}),
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
],
})
export class AppModule {}
Other packages similar to @auth0/angular-jwt
angular2-jwt
angular2-jwt is another Angular library for handling JWTs. It provides similar functionalities such as token decoding, token expiration checking, and HTTP request interception. However, @auth0/angular-jwt is more actively maintained and has better integration with Auth0 services.
ngx-auth
ngx-auth is a comprehensive authentication library for Angular that supports JWT. It provides features for token management, HTTP request interception, and route guarding. Compared to @auth0/angular-jwt, ngx-auth offers a more extensive set of features for handling authentication flows.
ngx-jwt-auth
ngx-jwt-auth is another Angular library focused on JWT authentication. It provides utilities for token storage, token expiration checking, and HTTP request interception. While it offers similar functionalities to @auth0/angular-jwt, it is less popular and has fewer community contributions.
@auth0/angular-jwt
This library provides an HttpInterceptor
which automatically attaches a JSON Web Token to HttpClient
requests.
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.
Note: This library can only be used with Angular 4.3 and higher because it relies on an HttpInterceptor
from Angular's HttpClient
. This feature is not available on lower versions.
Installation
npm install @auth0/angular-jwt@beta
yarn add @auth0/angular-jwt@beta
Usage
Import the JwtModule
module and add it to your imports list. Call the forRoot
method and provide a tokenGetter
function. You must also whitelist any domains that you want to make requests to by specifying a whitelistedDomains
array.
Be sure to import the HttpClientModule
as well.
import { JwtModule } from '@auth0/angular-jwt';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
bootstrap: [AppComponent],
imports: [
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem('access_token');
},
whitelistedDomains: ['localhost:3001']
}
})
]
})
export class AppModule {}
Any requests sent using Angular's HttpClient
will automatically have a token attached as an Authorization
header.
import { HttpClient } from '@angular/common/http';
export class AppComponent {
constructor(public http: HttpClient) {}
ping() {
this.http.get('http://example.com/api/things')
.subscribe(
data => console.log(data),
err => console.log(err)
);
}
}
Configuration Options
tokenGetter: function
The tokenGetter
is a function which returns the user's token. This function simply needs to make a retrieval call to wherever the token is stored. In many cases, the token will be stored in local storage or session storage.
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem('access_token');
}
}
})
whitelistedDomains: array
Authenticated requests should only be sent to domains you know and trust. Many applications make requests to APIs from multiple domains, some of which are not controlled by the developer. Since there is no way to know what the API being called will do with the information contained in the request, it is best to not send the user's token any and all APIs in a blind fashion.
List any domains you wish to allow authenticated requests to be sent to by specifying them in the the whitelistedDomains
array.
JwtModule.forRoot({
config: {
whitelistedDomains: ['localhost:3001', 'foo.com', 'bar.com']
}
})
Note: If requests are sent to the same domain that is serving your Angular application, you do not need to add that domain to the whitelistedDomains
array. However, this is only the case if you don't specify the domain in the Http
request.
For example, the following request assumes that the domain is the same as the one serving your app. It doesn't need to be whitelisted in this case.
this.http.get('/api/things')
.subscribe(...)
However, if you are serving your API at the same domain as that which is serving your Angular app and you are specifying that domain in Http
requests, then it does need to be whitelisted.
this.http.get('http://localhost:4200/api/things')
.subscribe(...)
The default header name is Authorization
. This can be changed by specifying a custom headerName
which is to be a string value.
JwtModule.forRoot({
config: {
headerName: 'Your Header Name'
}
})
authScheme: string
The default authorization scheme is Bearer
followed by a single space. This can be changed by specifying a custom authScheme
which is to be a string.
JwtModule.forRoot({
config: {
authScheme: 'Your Auth Scheme'
}
})
throwNoTokenError: boolean
Setting throwNoTokenError
to true
will result in an error being thrown if a token cannot be retrieved with the tokenGetter
function. Defaults to false
.
JwtModule.forRoot({
config: {
throwNoTokenError: true
}
})
skipWhenExpired: boolean
By default, the user's JWT will be sent in HttpClient
requests even if it is expired. You may choose to not allow the token to be sent if it is expired by setting skipWhenExpired
to true.
JwtModule.forRoot({
config: {
skipWhenExpired: true
}
})
What is Auth0?
Auth0 helps you to:
- Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
- Add authentication through more traditional username/password databases.
- Add support for linking different user accounts with the same user.
- Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
- Analytics of how, when and where users are logging in.
- Pull data from other sources and add it to the user profile, through JavaScript rules.
Create a free Auth0 account
- Go to Auth0 and click Sign Up.
- Use Google, GitHub or Microsoft Account to login.
Issue Reporting
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.
Author
Auth0
License
This project is licensed under the MIT license. See the LICENSE file for more info.