angular2-jwt is a helper library for working with JWTs in your Angular 2 applications.
For examples of integrating angular2-jwt with SystemJS, see auth0-angular2.
- What is this Library for?
- Key Features
- Basic Configuration
- Sending Authenticated Requests
- Configuration Options
- Checking Authentication to Hide/Show Elements and Handle Routing
- What is Auth0?
- Create a free account in Auth0
- Issue Reporting
What is this Library for?
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.
- Send a JWT on a per-request basis using the explicit
- Decode a JWT from your Angular 2 app
- Check the expiration date of the JWT
- Conditionally allow route navigation based on JWT status
npm 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 requests
tokenNotExpired- 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 authenticated
Create a new
auth.module.ts file with the following code:
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.
Sending Authenticated Requests
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.
AUTH_PROVIDERS gives a default configuration setup:
- Header Name:
- Header Prefix:
- Token Name:
- Token Getter Function:
(() => localStorage.getItem(tokenName))
- Supress error and continue with regular HTTP request if no JWT is saved:
- Global Headers: none
If you wish to configure the
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
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
You may set as many global headers as you like by passing an array of header-shaped objects to
You may customize any of the above options using a factory which returns an
AuthHttp instance with the options you would like to change.
Configuration for Ionic 2
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.
Sending Per-Request Headers
You may also send custom headers on a per-request basis with your
authHttp request by passing them in an options object.
Using the Observable Token Stream
If you wish to use the JWT as an observable stream, you can call
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.
Using JwtHelper in Components
JwtHelper class has several useful methods that can be utilized in your components:
You can use these methods by passing in the token to be evaluated.
jwtHelper: JwtHelper = new JwtHelper;useJwtHelper
Checking Authentication to Hide/Show Elements and Handle Routing
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,
true, otherwise it returns
tokenNotExpiredwill by default assume the token name is
tokenunless 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 in
loggedIn method can now be used in views to conditionally hide and show elements.
Log InLog Out
To guard routes that should be limited to authenticated users, set up an
With the guard in place, you can use it in your route configuration.
Pull requests are welcome!
npm run dev to compile and watch for changes.
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, among 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.
Create a free account in Auth0
- Go to Auth0 and click Sign Up.
- Use Google, GitHub or Microsoft Account to login.
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.