When making an XMLHttpRequest to an API secured with OAuth authentication, I encountered a situation where calling the API from a browser without being logged in automatically redirected me to the provider's login page.
However, when attempting to call the API from a web app using an XMLHttpRequest in Chrome, I received the following error message:
DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load https://localhost/myapp/api/AppConfig
XMLHttpRequest cannot load …. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.
This led me to realize that I need to determine if I am logged in and if not, open the login window in a new tab.
My main challenge now is how to reliably detect whether I am logged in and if the XMLHttpRequest is being forwarded - taking into consideration various browsers and cors settings.
try {
xhr.send(null);
} catch(ex) {
// Is there a way to distinguish between an authentication issue and another type of problem?
}