siddhant3s
siddhant3s

Reputation: 420

Not able to access authorization required resource with jquery's ajax

I have a webdav host on my server called sidunhosted.com/ungdav/test.json (It's a virtual host)

I have Basic authorization on /ungdav/. This is my .htaccess file for sidunhosted.com/ungdav/ .

AuthType Basic
AuthName "your unhosted data"
AuthUserFile /srv/http/sidunhosted.com/ungdav/.htpasswd

Require valid-user

Header always set Access-Control-Allow-Methods "GET, POST, DELETE, OPTIONS, PUT"
Header always set Access-Control-Allow-Headers "Content-Type, X-Requested-With, X-HTTP-Method-Override, Accept, Authorization"
Header always set Access-Control-Allow-Credentials "true"
Header always set Cache-Control "max-age=0"
Header always set Access-Control-Allow-Origin *

I'm using following jQuery code (with firebug) to access the resource

$.ajax({
                        url: "http://sidunhosted.com/ungdav/test.json",
                        cache: false,
                        dataType: "text",
                        headers: {Authorization: "Basic "+btoa("smik:asdf")},
                        fields: {withCredentials: "true"},
                        success: function(text){
                                alert(text);
                        }
});

This works if I am on sidunhosted.com (Dump of interaction: http://paste.pocoo.org/show/417127/). But doesn't work(returns Authorization required) if I call that from some other website (Dump of interaction: http://paste.pocoo.org/show/417128/) i.e. execute this code on firebug console while being on some other website (which have jQuery loaded).

Upvotes: 1

Views: 1667

Answers (1)

siddhant3s
siddhant3s

Reputation: 420

Finally found the answer (after 8 hours) The problem is that for CORS requests, the browser must have access to OPTIONS and HEAD method even without authentication. Hence to make the above work, we have to bind the Require valid-user in a <LimitExcept> block like this

<LimitExcept OPTIONS HEAD>
  Require valid-user
</LimitExcept>

This ensures that the browser can read OPTIONS and HEAD without being authenticated.

Upvotes: 2

Related Questions