I am curious about how to handle ajax failures caused by OIDC SSO redirect/refresh. It can be tricky because the failure happens silently, giving the impression that everything is functioning correctly.
My website consists of static HTML and basic javascript that uses ajax to populate and refresh the page periodically.
Both the webpage and JS are protected by the same OIDC SSO for access control. However, there are scenarios where the ajax call fails with a 401 error due to needing an authentication refresh (not full password authentication).
Both the backend and frontend are hosted on the same server using Apache with identical Access Control and Authorization requirements.
- If a user loads a cached version of the HTML and only the ajax request is triggered (e.g., using the back button).
- If the page remains idle for a certain period, I suspect that even regular refreshes may fail for the same reason.
I have implemented a workaround shown below, but it seems like a makeshift solution, and I believe there must be a better standard practice for handling this issue.
// This function runs every 30 seconds
function updateData(args, callback) {
$.ajax({
xhrFields: { withCredentials: true },
url: "/getit?" + args,
success: function(data) {
localStorage.removeItem('pagereloaded')
callback(data);
},
statusCode: {
// Reload is needed when SSO tokens expire, causing ajax failure.
// If it's just an auth failure, we don't want to create an infinite reload loop.
// So 'pagereloaded' and timers are used to avoid continuous reloading.
401: function () {
if (localStorage.getItem('pagereloaded') == null || (Date.now() - start_time) > 60000) {
localStorage.setItem("pagereloaded", 1)
location.reload();
}
}
}
});
}