darkknight
darkknight

Reputation: 216

How to prevent jwt token getting lost on page refresh in an angularjs application?

I am trying to authorize a user using jwt token. But if i refresh the page, the jwt gets lost and the token is not sent on subsequent requests to the server. I am using localstorage for storing the token and spring-mvc for backend. This is the service i have created:

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

Upvotes: 4

Views: 2895

Answers (1)

Raghu Venmarathoor
Raghu Venmarathoor

Reputation: 868

You have to use this if you are already logged in.

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

Upvotes: 1

Related Questions