4

enter image description here

I am using the Angular-satellizer extension for the login/register feature but I am stuck at number 7.

Token was saved to localStorage but I when refresh the page it's gone and $auth.isAuthenticated() function is returning false.

enter image description here

.controller('loginCtrl', function($scope, $state, $auth, jwtHelper) {
  $scope.login = function() {
    $auth.login($scope.user)
      .then(function(response) {
        var gelenToken = response.data;
        var tokenPayload = jwtHelper.decodeToken(gelenToken.token);
        console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}
        localStorage.setItem('token', JSON.stringify(tokenPayload));
        $state.go('baba.manga');
      })
  };
})
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
Nasuh
  • 355
  • 3
  • 20

2 Answers2

3

You should try this :

localStorage.setItem('token', data.token);

OR

$window.localStorage.token = JSON.stringify(data.token);

to save your token, You can see the token in browser local Storage, You don't need to decode that token unless you need it to.

It should not get deleted on page refresh, If its getting deleted the I suggest you to try breakpoints at places and debug which part is clearing local storage.

Browser does not delete any localstorage data at any point, Your code might be doing it.

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
  • Satellizer manuel says `Parse the token and save it to localStorage`. Parse mean decode right? – Nasuh Jun 05 '17 at 19:32
  • I don't think so, parse means extract and save, not decode,you have to send encoded token to server not decoded. – Sangwin Gawande Jun 05 '17 at 19:34
  • Ok. I find the issue. token only saved for `login.html` not for all pages. Now I need to share the token with `index.html` or `$scope.isAuthenticated = function()` share this function with `index.html`'s state. Which is better? – Nasuh Jun 05 '17 at 20:17
  • Satellizer has its own function `$auth.setToken(token)` and this saves the token for the all pages. Thank you. – Nasuh Jun 05 '17 at 20:35
1

Maybe when you refresh the page , you are reseting the localStorage and your last token gone.

Try this

// if the localScore is not set then initialize it 
if(localStorage.getItem('token') === null) {
     localStorage.setItem('token', JSON.stringify(tokenPayload));
}
Amadou Beye
  • 2,538
  • 3
  • 16
  • 37