我想授權使用jwt令牌的用戶。但是,如果我刷新頁面,那麼jwt會丟失,並且在後續對服務器的請求中不會發送令牌。我使用localstorage來存儲令牌和後端的spring-mvc。 這是我創建的服務:如何在angularjs應用程序中防止頁面刷新時丟失jwt令牌?
'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();
}
}]);
餅乾/網絡存儲(localStorage的/的sessionStorage) –
localstore不會被清除的。頁面刷新。您是如何在$ http請求上設置令牌的? –