Skip to content

PatrickJS/angular-jwt

Repository files navigation

angular-jwt

This library will help you work with JWTs. It's comprehended of 2 basic services

Installing it

You have several options:

bower install angular-jwt
npm install angular-jwt
<scripttype="text/javascript" src="https://rawgit.com/auth0/angular-jwt/master/dist/angular-jwt.js"></script>

jwtHelper

jwtHelper will take care of helping you decode the token and check its expiration date.

Decoding the token

functionController(jwtHelper){varexpToken='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8';vartokenPayload=jwtHelper.decodeToken(expToken);}

Getting the token expiration date

functionController(jwtHelper){vardate=jwtHelper.getTokenExpirationDate(expToken);}

Checking if token is expired

functionController(jwtHelper){varbool=jwtHelper.isTokenExpired(expToken);}

More examples

You can see some more examples of how this works in the tests

jwtInterceptor

JWT interceptor will take care of sending the JWT in every request.

Basic usage

functionConfig($httpProvider,jwtInterceptorProvider){jwtInterceptorProvider.tokenGetter=function(localStorage){returnlocalStorage.getItem('id_token');}$httpProvider.interceptors.push('jwtInterceptor');}functionController($http){// If localStorage contains the id_token it will be sent in the request// Authorization: Bearer [yourToken] will be sent$http({url: '/hola',method: 'GET'});}

Using promises on the tokenGetter: Refresh Token example

As sometimes we need to get first the id_token in order to send it, we can return a promise in the tokenGetter. Let's see for example how we'd use a refresh_token

functionConfig($httpProvider,jwtInterceptorProvider){jwtInterceptorProvider.tokenGetter=function(localStorage,jwtHelper){varidToken=localStorage.getItem('id_token');varrefreshToken=localStorage.getItem('refresh_token');if(jwtHelper.isTokenExpired(idToken)){// This is a promise of a JWT id_tokenreturnauth.refreshToken(refreshToken).then(function(id_token){localStorage.setItem('id_token',id_token);returnid_token;});}else{returnidToken;}}$httpProvider.interceptors.push('jwtInterceptor');}functionController($http){// Authorization: Bearer [yourToken] will be sent. // That token might be a new one which was got from the refresh token$http({url: '/hola',method: 'GET'});}

More examples

You can see some more examples of how this works in the tests

Contributing

Just clone the repo, run npm install, bower install and then gulp to work :).

License

MIT

About

Library to help you work with JWTs on AngularJS

Resources

License

Stars

Watchers

Forks

Packages

No packages published