Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
angular-jwt
Advanced tools
Readme
This library will help you work with JWTs.
You have several options:
bower install angular-jwt
npm install angular-jwt
<script type="text/javascript" src="https://cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt.js"></script>
jwtHelper will take care of helping you decode the token and check its expiration date.
angular
.module('app', ['angular-jwt'])
.controller('Controller', function Controller(jwtHelper) {
var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8';
var tokenPayload = jwtHelper.decodeToken(expToken);
});
angular
.module('app', ['angular-jwt'])
.controller('Controller', function Controller(jwtHelper) {
var date = jwtHelper.getTokenExpirationDate(expToken);
});
angular
.module('app', ['angular-jwt'])
.controller('Controller', function Controller(jwtHelper) {
var bool = jwtHelper.isTokenExpired(expToken);
});
You can see some more examples of how this works in the tests
JWT interceptor will take care of sending the JWT in every request.
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
// Please note we're annotating the function so that the $injector works when the file is minified
jwtOptionsProvider.config({
tokenGetter: ['myService', function(myService) {
myService.doSomething();
return localStorage.getItem('id_token');
}];
});
$httpProvider.interceptors.push('jwtInterceptor');
})
.controller('Controller', function Controller($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'
});
});
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
// Please note we're annotating the function so that the $injector works when the file is minified
jwtOptionsProvider.config({
tokenGetter: ['myService', function(myService) {
myService.doSomething();
return localStorage.getItem('id_token');
}];
});
$httpProvider.interceptors.push('jwtInterceptor');
})
.controller('Controller', function Controller($http) {
// This request will NOT send the token as it has skipAuthentication
$http({
url: '/hola',
skipAuthorization: true,
method: 'GET'
});
});
If you are calling an API that is on a domain other than your application's origin, you will need to whitelist it.
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
...
whiteListedDomains: ['api.myapp.com', 'localhost']
});
The tokenGetter
method can have a parameter options
injected by angular-jwt. This parameter is the options object of the current request.
By default the interceptor will send the JWT for all HTTP requests. This includes any ng-include
directives or
templateUrls
defined in a state
in the stateProvider
. If you want to avoid sending the JWT for these requests you
should adapt your tokenGetter
method to fit your needs. For example:
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
tokenGetter: ['options', function(options) {
// Skip authentication for any requests ending in .html
if (options.url.substr(options.url.length - 5) == '.html') {
return null;
}
return localStorage.getItem('id_token');
}]
});
$httpProvider.interceptors.push('jwtInterceptor');
});
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
tokenGetter: ['options', function(options) {
if (options.url.indexOf('http://auth0.com') === 0) {
return localStorage.getItem('auth0.id_token');
} else {
return localStorage.getItem('id_token');
}
}]
});
$httpProvider.interceptors.push('jwtInterceptor');
})
.controller('Controller', function Controller($http) {
// This request will send the auth0.id_token since URL matches
$http({
url: 'http://auth0.com/hola',
skipAuthorization: true,
method: 'GET'
});
}
Almost all applications that implement authentication need some indication of whether the user is authenticated or not. The authManager service provides a way to determine if users are authenticated or not. This can be useful for conditionally showing and hiding different parts of the UI.
<button ng-if="!isAuthenticated">Log In</button>
<button ng-if="isAuthenticated">Log Out</button>
The authentication state that is set after login will only be good as long as the user doesn't refresh their page. If the page is refreshed, or the browser closed and reopened, the state will be lost. To check whether the user is actually authenticated when the page is refreshed, use the checkAuthOnRefresh
method in the application's run
block.
angular
.module('app')
.run(function(authManager) {
authManager.checkAuthOnRefresh();
});
When the user's JWT expires and they attempt a call to a secured endpoint, a 401 - Unauthorized response will be returned. In these cases you will likely want to redirect the user back to the page/state used for authentication so they can log in again. This can be done with the redirectWhenUnauthenticated
method in the application's run
block.
angular
.module('app')
.run(function(authManager) {
...
authManager.redirectWhenUnauthenticated();
});
The page/state to send the user to when they are redirected because of an unauthorized request can be configured with jwtOptionsProvider
.
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
unauthenticatedRedirectPath: '/login'
});
If you would like to control the behavior of the redirection that happens when users become unauthenticated, you can configure jwtOptionsProvider
with a custom function.
angular
.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
unauthenticatedRedirector: ['$state', function($state) {
$state.go('app.login');
}]
});
angular.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
jwtOptionsProvider.config({
urlParam: 'access_token',
tokenGetter: ['myService', function(myService) {
myService.doSomething();
return localStorage.getItem('id_token');
}]
});
$httpProvider.interceptors.push('jwtInterceptor');
})
.controller('Controller', function Controller($http) {
// If localStorage contains the id_token it will be sent in the request
// url will contain access_token=[yourToken]
$http({
url: '/hola',
method: 'GET'
});
})
You can see some more examples of how this works in the tests
When you're using the tokenGetter
function, it's then called with the injector. ngAnnotate
doesn't automatically detect that this function receives services as parameters, therefore you must either annotate this method for ngAnnotate
to know, or use it like follows:
jwtOptionsProvider({
tokenGetter: ['store', '$http', function(store, $http) {
...
}];
});
This library is used in auth0-angular and angular-lock.
Just clone the repo, run npm install
, bower install
and then gulp
to work :).
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.
Auth0 helps you to:
This project is licensed under the MIT license. See the LICENSE file for more info.
FAQs
Library to help you work with JWTs on AngularJS
The npm package angular-jwt receives a total of 7,422 weekly downloads. As such, angular-jwt popularity was classified as popular.
We found that angular-jwt demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers 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.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.