I pass a Json Web Token in the Authorization header upon every request and store it in Local Storage. When the user clicks "Logout", it deletes the token in local storage and i even log it in the console and it says null. But upon the next requests the Authorization header will still use the Json Web Token even though it is deleted. It is not until i hit the refresh button on the browser that it will take effect and the requests will start using the updated value. I am building a Single Page App with Angular.js.
This is how i am setting the local storage:
User.authUser($scope.credentials).then(function(res) {
console.log(res);
if(res.success === true){
console.log('User is authenticated!');
localStorage.setItem('jwt', JSON.stringify(res.token));
} else {
console.log('User is NOT authenticated.');
}
});
This is how i am setting the Authorization header and deleting local storage:
angular.module('App.user', [])
.factory('User', function($http, $location, $state, $window) {
var jwt = localStorage.getItem('jwt');
$http.defaults.headers.common.Authorization = JSON.parse(jwt);
var apiUrl = 'http://localhost:8080/api';
return {
authUser: function(credentials) {
return $http.post(apiUrl + '/authenticate', credentials).then(function(res){
return res.data;
});
},
getMe: function() {
return $http.get(apiUrl + '/users/me').then(function(res) {
return res.data;
});
},
logOut: function(){
console.log('Logging user out');
localStorage.removeItem('jwt');
$state.go('home');
}
};
});
On each page i use the method above User.getMe() to check if the user is valid. So one of the problems is when the user is logged into their profile, then they hit logout(which deletes the storage), they are redirected to the home page BUT the home page uses "User.getMe()" to check if user is logged in and since the Authorization header is still using the old JWT, it says the user is logged in. It will only work when i manually refresh the page.
i have googled around for multiple hours and cannot find anything. When i logged the 'jwt' from localstorage in the console it says null but when i check the requests in Chrome's developer tools it shows that the requests are still using the old json web token.
I thought maybe the pages were being cached and that was why so i tried to turn off caching but that did not help.
Any help is appreciated!
The reason is you have already assigned it to $http.defaults.headers
.
At that point removing or changing the stored token will do nothing to the default headers.
Using an httpInterceptor to set header would get around this