My project involves authorizing users using jwt tokens, but I am facing an issue where the token is lost upon page refresh and subsequent requests to the server do not include the token. The setup includes storing the token in local storage and utilizing spring-mvc for the backend. Below is the service I've implemented:
'use strict';
angular.module('authentication')
.factory('AuthenticationService', ['$http', '$localStorage',
'$rootScope','$route', '$q', function($http, $localStorage, $rootScope,
$route, $q){
var service = {loggedInUser: function(){
return $q.when($rootScope.user)
}};
service.Login = Login;
service.Logout = Logout;
return service;
function Login(username, password, callback){
$http.post('http://172.16.0.26:7001/Taisys_Server_Current/auth',
{username:username, password:password})
.success(function (response){
if(response.token){
$localStorage.currentUser = {username:username,
token:response.token};
$http.defaults.headers.common.Authorization = 'Bearer' + response.token;
$rootScope.user= $localStorage.currentUser;
$rootScope.token = response.token;
callback(true);
}
else{
callback(false);
}
});
}
function Logout(){
delete $localStorage.currentUser;
$http.defaults.headers.common.Authorization = '';
$route.reload();
}
}]);