javascript – 如何防止在angularjs应用程序中页面刷新时jwt令牌丢失?

我正在尝试使用jwt令牌授权用户.但是如果我刷新页面,jwt就会丢失,并且在后续的服务器请求中不会发送令牌.我使用localstorage存储令牌和
spring-mvc用于后端.

这是我创建的服务:

'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();
  }
  }]);

最佳答案 如果您已经登录,则必须使用此功能.

$http.defaults.headers.common.Authorization = 'Bearer' + $localStorage.currentUser.token;
点赞