When I start up an application I am writing, it loads the appropriate user data from the server. When I refresh the page, it doesn't load my table, and it states in the server logs that the authorisation code is invalid and throws a 403 error.
if (authorisation_code && token_type !== null) {
// Post acces code and token
function postAuthorisationCode() {
let data = {
authorisation_code: authorisation_code,
token_type: token_type
};
let pac_url = "/lib/post-request-1.php";
fetch(uriRoot+pac_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
// console.log(response);
response.text().then((rdata) => {
// console.log(rdata);
// Get length
let rdataLen = rdata.length;
// Slice 200 status off by starting index 4.
let obj = rdata.slice(4, rdataLen);
// Parse string into an object.
let returnObj = JSON.parse(obj);
// Set variables
let access_token = returnObj.access_token;
// Invoke postAccessToken function
postAccessToken(access_token);
})
})
}
// Function call
postAuthorisationCode();
function postAccessToken(access_token) {
let pat_url = "/lib/get-request-2.php";
// TODO: Eventually will include authorisation_code...
fetch(uriRoot+pat_url, {
method: "POST",
headers: {
Accept: "application/json",
},
body: access_token
})
.then((response) => {
console.log(response);
response.text().then((rdata) => {
console.log(rdata);
})
userTable();
})
.catch((error) => {
console.log(error);
})
}
NB: userTable takes the data and puts it into a table!
Can anyone spot any errors in my code why it works when you initially load, but fails to work after a refresh?
From my research and understanding the authorisation code flow: Authorisation Code Flow it appears that the failure is occurring at stage 10 only when the page has been refreshed. The server returns 403 invalid authorisation code, and I believe that is because authorisation codes are one time use. I would need to implement a refresh token in order to refresh the page without losing data. My proposed solution is as follows: (this is because my business required that refresh tokens were not implemented yet)
On when a refresh has been invoked, throw an alert that warns the user they will lose data and prompts them to click to either cancel the operation or continue with it. If they user has decided to continue with the operation, the user will be redirected to the login page, where they can log in, and the order of operations in the Authorisation Code flow work as intended.
If the customer refreshes, this code will handle it:
<script type="text/javascript">
window.onbeforeunload = function() {
return "Data will be lost if you leave the page, are you sure?";
}
</script>
if (response.status !== 200) {
// console.log(response.status);
window.location.replace("...url here...");
}
The 1st piece of code goes into the HTML doc, whilst the second piece will go into your JS. Mine in particular is looking for any status code that is NOT a 200.