Check if same origin policy applies

♀尐吖头ヾ 提交于 2019-12-17 22:15:21

问题


Is there a "safe" way to check if the same origin policy applies to an URL before actually trying to use ajax methods? Here is what I have:

function testSameOrigin(url) {

    var loc = window.location,
        a = document.createElement('a');

    a.href = url;

    return a.hostname == loc.hostname &&
           a.port == loc.port &&
           a.protocol == loc.protocol;
}

This sort of works, but it’s kind of a manual guess based on the wikipedia article. Is there a better way of pre-checking cross domain allowance? jQuery is OK to use.


回答1:


Interesting question! I searched around and couldn't find anything other than what you posted, but I did come across this when I was messing around with some test code. If you just want a simple way to test a URL without making a request, I'd do it the way you're doing it. If you don't care about making a request to test, you could try this:

Make a simple ajax request to whatever URL you want:

var ajaxRequest = $.ajax({
  url: 'http://www.google.com',
  async: false
});

which returns a jqXHR object, which you can then check:

ajaxRequest.isRejected(); // or...
ajaxRequest.isResolved();

Now, the only problem with this is that isRejected() will evaluate to true for every single case where the page doesn't load (i.e. 404 Not Found, etc.), but you can check the status code with:

ajaxRequest.status;

It looks like the above line will return 0 when you attempt to break the same origin policy, but it will return the appropriate error code (again, i.e. 404) in other cases.

So to wrap up, maybe you could try doing something like:

function testSameOrigin(testUrl) {

  var ajaxRequest = $.ajax({
    url: testUrl,
    async: false
  });

  return ajaxRequest.isRejected() && ajaxRequest.status === 0;
}

Not a definitive answer by any means, but I hope it helps you figure out what you're looking for!




回答2:


Is there a "safe" way to check if the same origin policy applies to an URL before actually trying to use ajax methods? Here is what I have:

function testSameOrigin(url) {

    var loc = window.location,
        a = document.createElement('a');

    a.href = url;

    return a.hostname == loc.hostname &&
           a.port == loc.port &&
           a.protocol == loc.protocol;
}

This is a safe and reliable way of doing it, provided you are doing (or rather not doing) certain things.

This sort of works, but it’s kind of a manual guess based on the wikipedia article.

This should fully work under the "normal" circumstances. It will need to be modified if you are planning to use cross-domain scripting.

If you modify document.domain in your scripts, for example from "foo.example.com" and "bar.example.com" to "example.com" your testSameOrigin function would return false for "http://example.com", where in fact it should return true.

If you are planning on modifying document.domain, you can add simply add a check for that in your script.

If you are planning on using CORS (see the link above) to allow cross-domain communication, it will also return a false negative. But if you are using CORS, you will have a list of domains that you can communicate with, and you can add that list to this function as well.

Is there a better way of pre-checking cross domain allowance? jQuery is OK to use.

Probably not, although it may be worth mentioning that what you are seeing in the console from Steve's answer might be the "observer's dilemma" ... Those errors look like they are resulting from the console trying to inspect the other window, not necessarily from the script.

Assuming you're not messing with document.domain or using CORS, your original solution is probably better, as it doesn't need to make an extra request to determine whether the server is available or not. Even if you are doing some cross-domain scripting, modifying the function you have now to accommodate it is probably your best bet.




回答3:


Try this solution as well.

function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

function sameOrigin(url) {
  // test that a given url is a same-origin URL
  // url could be relative or scheme relative or absolute
  var host = window.document.location.host; // host + port
  var protocol = window.document.location.protocol;
  var srOrigin = '//' + host;
  var origin = protocol + srOrigin;
  // Allow absolute or scheme relative URLs to same origin
  return (url === origin || url.slice(0, origin.length + 1) === origin + '/') ||
    (url === srOrigin || url.slice(0, srOrigin.length + 1) === srOrigin + '/') ||
    // or any other URL that isn't scheme relative or absolute i.e relative.
    !(/^(\/\/|http:|https:).*/.test(url));
}

// if you want to check before you make a call
if (!csrfSafeMethod(data.type) && sameOrigin(data.url)) {
  // ...
}

// or if you want to set csrf token
$.ajax({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
      xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
    }
  }
});



回答4:


Another way to execute cross domain script is using JSON-P. You can also read this article. Otherwise, the cross domain scripting is not allowed by the same origin policy.




回答5:


Building off of Dagg Nabbit's answer, this seems a little more complete:

function sameOrigin(url) {
    var loc = window.location, a = document.createElement('a')
    a.href = url

    return a.hostname === loc.hostname &&
           a.port === loc.port &&
           a.protocol === loc.protocol &&
           loc.protocol !== 'file:'
}

Caveats I can think of:

  • doesn't take document.domain into account
  • doesn't take CORS into account
  • Doesn't work in IE7 (as mentioned by zanona)
  • Doesn't work in weird environments (like android) where you can access arbitrary file:// protocol paths (someone please verify this, the info about android might be outdated https://security.stackexchange.com/questions/25138/same-origin-policy-for-file-urls-in-android-browser)


来源:https://stackoverflow.com/questions/9404793/check-if-same-origin-policy-applies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!