Web API Redirect – How to Handle a Redirect to an Identity Provider During a Web API Data Request

ajaxjavascriptoauthrest

Scenario

I have a single-page web app consisting purely of html, css, and javascript. After initial load and during use, it updates various views with data from one or more RESTful apis via ajax calls. The api calls return data in a json format. Each web api may be hosted on independent domains.

Question

During the ajax callout, if my authorization token is not deemed valid by the web api, the web api will redirect me (302) to the identity provider for that particular api. Since this is an ajax callout for data and not necessarily for display, i need to find a way to display the identity provider's authentication page. It seems that I should trap that redirect, and open up another view to display the identity provider's login page. Once the oauth series of redirects is complete, i need to grab the token and retrigger my ajax data call with the token attached.

Is this a valid approach, and if so are there any examples showing the ajax handling of the redirects?

Best Answer

Redirects happen transparent to the calling JavaScript. Detecting a redirect from JavaScript is not (universally) possible. However, there are two things you can do:

  1. Detect the returned data is not JSON (but HTML) and re-open the URL using a popup or iframe, and handle the authentication.
  2. Modify your web API to return a 401 Unauthorized header for invalid requests. The body of that response can contain the designated URL for authentication which your JavaScript can handle using a popup or iframe (like with 1.).