Recently, I created a demo for a basic Login and Logout application that utilizes an access token. If a user attempts to access another page without logging in (meaning the access token is null), they are redirected back to the Login page. Initially, I used sessionStorage to store the user token and everything worked smoothly. However, when I switched to using localStorage instead, my application ceased functioning properly. Although the login process still completes successfully, there is a brief moment where I am redirected back to the Login page as if the token was not saved at all. Subsequently, even after generating a new token post-login, it seems like there is an issue specifically related to localStorage.
Update: Upon further investigation, it appears that both storage methods do save the token, but I encountered difficulties passing it to other pages when using localStorage.
This is a snippet of code from my Login Page:
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Upon successful login, store the token in localStorage
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 any errors in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
This part shows the base code from another page:
if (localStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}