2

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.

Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.

My Login Page Code:

$('#btnLogin').click(function () {
            $.ajax({
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    userName: $('#txtFullname').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },
                // Khi đăng nhập thành công, lưu token vào sessionStorage
                success: function (response) {
                    //sessionStorage.setItem("accessToken", response.access_token);
                    localStorage.setItem("accessToken", response.access_token);
                    window.location.href = "User.html";
                    //$('#divErrorText').text(JSON.stringify(response));
                    //$('#divError').show('fade');
                },
                // Display errors if any in the Bootstrap alert <div>
                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });

Other page base code:

if (localStorage.getItem('accessToken') == null) {
            window.location.href = "Login.html";
        }
  • does this `localStorage.getItem('accessToken')` print `null ` but `sessionStorage.getItem('accessToken') ` print some value? – ABGR Jun 06 '20 at 08:30
  • I just checked back and they both storage my token but I can't parse it to other pages with localStorage. –  Jun 06 '20 at 08:38
  • can you put `debugger` in success method and check the response please – Dupinder Singh Jun 06 '20 at 08:39

3 Answers3

0

Are you sure that response.access_token does not come null?

You can check it from the development tools in Chrome (Windows: Ctrl + Shift + i or macOs: command + option + i)> Application > Storage > Local Storage:

As you can see the value can be set null

As you can see the value can be set null.

I hope it helps.

Edgar Mejía
  • 119
  • 1
  • 9
0

localStorage supports only string values. Chances are response.access_token might not be a string value. So try this instead:

localStorage.setItem("accessToken", JSON.stringify(response.access_token));

And While retrieving,

JSON.parse(localStorage.getItem("accessToken"))

ABGR
  • 4,631
  • 4
  • 27
  • 49
0

Try to save object in localstorage use following method (as shown in https://stackoverflow.com/a/2010948)

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

And in your code we can do it like this

$('#btnLogin').click(function () {
            $.ajax({
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    userName: $('#txtFullname').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },
                // Khi đăng nhập thành công, lưu token vào sessionStorage
                success: function (response) {
                    var obj= { 'accessToken': response.access_token};
                    localStorage.setItem(JSON.stringify(obj));
                    window.location.href = "User.html";
                },
                // Display errors if any in the Bootstrap alert <div>
                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61