Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Redirect 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.).
share|improve this answer
    
Thanks bouke. Is there consensus in the community on which way is preferred? –  Erds Nov 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. –  bouke Nov 27 '12 at 12:34
    
After reviewing the options, I think it makes the most sense as well. –  Erds Dec 5 '12 at 20:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.