Angular JSON Web Token Authentication Module
Angular authentication with JSON Web tokens.
Intro
This module is for authenticating with a remote REST API, and attaching the auth token to all subsequent $http
xhr
requests to the API.
The module has the following features
- Basic (username/password) authentication
- Automatic token refreshing when it is about to expire,
- Persisting the token to
localstorage
so it is available between sessions - Token based authentication (useful for authenticating a confirmed registration email).
Installation
Install through npm:
npm install angular-jwt-auth --save
Usage
- Require the
ngJwtAuth
module in your angular application
angular.module'app',
- (Optionally) configure the service provider
angular.module'app', .config
- Inject the
ngJwtAuthService
, initialise it then use it! The init function loads any existing token from storage and kicks off the $interval that monitors the expiry status of the token.
It is highly recommended that you register a login prompt factory (See below), as this will allow the interceptor to prompt your users for their login details when an api request that returns status code 401.
angular.module'app', .run.controller'AppCtrl',
Login Prompt Factory
To handle prompting the user for authentication, angular-jwt-auth provides a registration method to allow the application to provide a function that resolves a deferred promise for user credentials, and returns a promise that the user has attempted authentication. The auth service will then attempt to log in with the resolved credentials. If an API call returns with a 401 response, the service will intercept the response, and login prompt function will run, giving the user a prompt to re-enter their credentials. If their login is successful, the API call that was previously rejected will be reattempted.
Full typescript example from the Spira project using a modal from angular materials $mdDialog
:
Note this example is in typescript, but it is the same process in plain javascript.
Todo
- Better documentation with examples in typescript.
- Site hosted on github showing off examples with material