如何绕过Access-Control-Allow-Origin?

发布于 2024-12-06 19:33:01 字数 806 浏览 1 评论 0 原文

我正在一个平台上对我自己的服务器进行ajax调用,他们设置了阻止这些ajax调用的平台(但我需要它从我的服务器获取数据以显示从我的服务器数据库检索到的数据)。 我的 ajax 脚本正在运行,它可以将数据发送到我的服务器的 php 脚本以允许其处理。 但是,它无法取回已处理的数据,因为它被“Access-Control-Allow-Origin”阻止,

我无法访问该平台的源代码/核心。所以我无法删除它不允许我这样做的脚本。 (P/SI使用Google Chrome的控制台发现了这个错误)

Ajax代码如下所示:

 $.ajax({
     type: "GET",
     url: "http://example.com/retrieve.php",
     data: "id=" + id + "&url=" + url,
     dataType: 'json',   
     cache: false,
     success: function(data)
      {
        var friend = data[1];              
        var blog = data[2];           
        $('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog);

      } 
  });

或者是否有与上面的ajax脚本等效的JSON代码?我认为 JSON 是允许的。

我希望有人能帮助我。

I'm doing a ajax call to my own server on a platform which they set prevent these ajax calls (but I need it to fetch the data from my server to display retrieved data from my server's database).
My ajax script is working , it can send the data over to my server's php script to allow it to process.
However it cannot get the processed data back as it is blocked by "Access-Control-Allow-Origin"

I have no access to that platform's source/core. so I can't remove the script that it disallowing me to do so.
(P/S I used Google Chrome's Console and found out this error)

The Ajax code as shown below:

 $.ajax({
     type: "GET",
     url: "http://example.com/retrieve.php",
     data: "id=" + id + "&url=" + url,
     dataType: 'json',   
     cache: false,
     success: function(data)
      {
        var friend = data[1];              
        var blog = data[2];           
        $('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog);

      } 
  });

or is there a JSON equivalent code to the ajax script above ? I think JSON is allowed.

I hope someone could help me out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

緦唸λ蓇 2024-12-13 19:33:01

将其放在retrieve.php 之上:

header('Access-Control-Allow-Origin: *');

请注意,这实际上会禁用 CORS 保护,并使您的用户面临攻击。如果您不完全确定需要允许所有来源,则应将其锁定到更具体的来源:

header('Access-Control-Allow-Origin: https://www.example.com');

请参阅以下堆栈答案以更好地理解Access-Control-此外,

您可以在此处阅读有关 CORS 的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

https://stackoverflow.com/a/10636765/413670

Put this on top of retrieve.php:

header('Access-Control-Allow-Origin: *');

Note that this effectively disables CORS protection, and leaves your users exposed to attack. If you're not completely certain that you need to allow all origins, you should lock this down to a more specific origin:

header('Access-Control-Allow-Origin: https://www.example.com');

Please refer to following stack answer for better understanding of Access-Control-Allow-Origin

Further more you can read more about CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

https://stackoverflow.com/a/10636765/413670

徒留西风 2024-12-13 19:33:01

警告,如果您遵循其他一些答案,Chrome(和其他浏览器)将抱怨设置了多个 ACAO 标头。

错误将类似于 XMLHttpRequest 无法加载 ____。 “Access-Control-Allow-Origin”标头包含多个值“____、____、____”,但只允许使用一个。因此,不允许访问来源“____”。

试试这个:

$http_origin = $_SERVER['HTTP_ORIGIN'];

$allowed_domains = array(
  'http://domain1.com',
  'http://domain2.com',
);

if (in_array($http_origin, $allowed_domains))
{  
    header("Access-Control-Allow-Origin: $http_origin");
}

Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.

The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.

Try this:

$http_origin = $_SERVER['HTTP_ORIGIN'];

$allowed_domains = array(
  'http://domain1.com',
  'http://domain2.com',
);

if (in_array($http_origin, $allowed_domains))
{  
    header("Access-Control-Allow-Origin: $http_origin");
}
丢了幸福的猪 2024-12-13 19:33:01

我在调用 MVC3 控制器时解决了这个问题。
我补充道:

Response.AddHeader("Access-Control-Allow-Origin", "*"); 

在我的之前

return Json(model, JsonRequestBehavior.AllowGet);

,我的 $.ajax 也抱怨它在我的 ajax 调用中不接受 Content-type 标头,所以我将其注释掉,因为我知道它JSON 正在传递给操作。

希望有帮助。

I have fixed this problem when calling a MVC3 Controller.
I added:

Response.AddHeader("Access-Control-Allow-Origin", "*"); 

before my

return Json(model, JsonRequestBehavior.AllowGet);

And also my $.ajax was complaining that it does not accept Content-type header in my ajax call, so I commented it out as I know its JSON being passed to the Action.

Hope that helps.

从来不烧饼 2024-12-13 19:33:01

使用 * 是一个非常糟糕的主意,它会让您对跨站点脚本敞开大门。您基本上始终需要自己的域,范围仅限于当前的 SSL 设置,以及可选的其他域。您还希望它们全部作为一个标头发送。以下内容将始终在与当前页面相同的 SSL 范围内授权您自己的域,并且还可以选择包含任意数量的其他域。它将把它们全部作为一个标头发送,如果已经发送了其他内容,则覆盖前一个标头,以避免浏览器抱怨发送的多个访问控制标头。

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

用法:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

你明白了。

It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

Usage:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

You get the idea.

梦醒灬来后我 2024-12-13 19:33:01

您是否尝试过将 Access-Control-Allow-Origin 标头实际添加到从服务器发送的响应中?比如,Access-Control-Allow-Origin: *

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文