9

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?

asked Nov 1, 2012 at 20:14
1

1 Answer 1

5

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.).
answered Nov 6, 2012 at 7:51
3
  • Thanks bouke. Is there consensus in the community on which way is preferred? Commented Nov 26, 2012 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. Commented Nov 27, 2012 at 12:34
  • After reviewing the options, I think it makes the most sense as well. Commented Dec 5, 2012 at 20:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.