I am passing my tokens to local storage, and I would like to retrieve them and authorize whether the user is able to enter the page or it is forbidden upon loading a new page. The thing is I do not know how to retrieve the token, I heard that passing/receiving it through headers would be necessary but I do not know how that process is done. Thank you in advance for your help :) This is my code for passing the token to the local storage:
function login(e){
e.preventDefault();
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
var details = {
'username': username,
'password': password,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://localhost:8080/login', {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: formBody
})
.then((res) => {
if(res.status == '200'){
return res.json();
}else{
alert("Incorrect login information")
}
})
.then((data) => {
let jwt = data.access_token
let jwtData = jwt.split('.')[1]
let decodedJwtJsonData = window.atob(jwtData)
let decodedJwtData = JSON.parse(decodedJwtJsonData)
let role = decodedJwtData.roles
if(role == "ADMIN"){
window.localStorage.setItem('access_token', data.access_token);
window.localStorage.setItem('refresh_token', data.refresh_token);
// Here would go the call to another site.
}
if(role == "MODERATOR"){
window.localStorage.setItem('access_token', data.access_token);
window.localStorage.setItem('refresh_token', data.refresh_token);
location.href = "moderatorHomepage.html";
}
window.localStorage.setItem('access_token', data.access_token);
window.localStorage.setItem('refresh_token', data.refresh_token);
if(role == "CUSTOMER"){
location.href = "homepage.html";
}
})
.catch(err =>{
console.error(err.message);
})