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?

1 Answer
1

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

Detect the returned data is not JSON (but HTML) and re-open the URL using a popup or iframe, and handle the authentication.

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.).

Thanks bouke. Is there consensus in the community on which way is preferred?
– ErdsNov 26 '12 at 23:17

I would go for 2; the first option might give unexpected results as content is not detected correctly. Also, calling the same URL twice feels hacky. However, if you do not control the API, 1 might be the only option.
– boukeNov 27 '12 at 12:34

After reviewing the options, I think it makes the most sense as well.
– ErdsDec 5 '12 at 20:10