开发者

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

开发者 https://www.devze.com 2023-03-15 05:17 出处:网络
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/ .

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://pas开发者_StackOverflow中文版te.pocoo.org/show/417128/) i.e. execute this code on firebug console while being on some other website (which have jQuery loaded).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号