UsAaR33
UsAaR33

Reputation: 3686

How do I permit cross-origin resource sharing selectively by authorization information?

Some users of my service wish to be able to access our REST API (which requires user credentials) via javascript in a browser. I will not allow this generally due to all of the vulnerabilities associated with violating the same origin policy. But if a specific user needs it and understands what is going on... I wish to add him to a "can make cross origin request" whitelist.

However, I cannot figure out how to selectively return a Access-Control-Allow-Origin header based on http authorization information.

If I do this in javascript:

$.ajax({'url':'url', 'beforeSend': function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + 'base64encodedcreds' ) } })

The browser first sends an ORIGIN METHOD request without the Authorization header. Consequently, there is no way for me to know if I should include Access-Control-Allow-Origin in the response.

Is there some setting in the xmlhttprequest to get it to send an ORIGIN with the authorization? Or is there another way to selectively grant cross-origin access?

Upvotes: 1

Views: 282

Answers (2)

UsAaR33
UsAaR33

Reputation: 3686

Based on duskwuff's answer that this was impossible I took this close route to not have to create new urls:

  • Always accept the options query with access-control-allow-origin
  • If a GET/POST comes in, check the options header. Check user credentials and 401 if user is not whitelisted.

(Very easy to pull off with django middleware)

Upvotes: 1

user149341
user149341

Reputation:

There's no way to bypass this behavior -- passing an authorization header is one of the bits of behavior that AAAO is trying to restrict. But you can sidestep it:

  • Create a separate endpoint URL for this user.
  • Have this endpoint always return an Access-Control-Allow-Origin that permits access. (Or whatever.)
  • Have this endpoint also always return 401 (not authorized) for any user other than the one you're trying to permit.

Upvotes: 1

Related Questions