'JWT implementation not working on angular js
I implemented JWT on my angular js application . I added the jwt authorization keys with all the http function . My codes are :
angular.module('IttadishopServices', [])
.config(function Config($httpProvider, jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter = function (User) {
var jwt = localStorage.getItem('id_token');
if (localStorage.getItem("id_token") === null) {
User.generateToken().success(function (data) {
localStorage.setItem('id_token', data);
return data;
});
} else {
return jwt;
}
}
$httpProvider.interceptors.push('jwtInterceptor');
});
Now Problem is , the authorization key is added on the header . but each request is send double to the server . I tried to add that authorization key many ways , but every time each request is sending double to the server , one request with the authorization key and another without any authorization key . Added an screenshot of console .
Solution 1:[1]
The problem is that you are not returning a promise in your intercepter and you are using a asynchronous function in that interceptor. So wrapping the asynch function in $q and returning a promise should fix the issue of 2 times sending the request. One time not waiting on the async function to complete (no key) and once when the promise of the User.generateToken() is resolved. Wrapping:
angular.module('IttadishopServices', [])
.config(function Config($httpProvider, jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter = function (User) {
var jwt = localStorage.getItem('id_token');
if (localStorage.getItem("id_token") === null) {
var deferred = $q.defer();
User.generateToken().success(function (data) {
localStorage.setItem('id_token', data);
deferred.resolve(data);
});
return deferred.promise;
} else {
return jwt;
}
}
$httpProvider.interceptors.push('jwtInterceptor');
});
But you shouldn't define that function in the config block, rather in a factory.
Source: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kenneth Van den Berghe |
