how to bypass Access-Control-Allow-Origin?
Asked Answered
U

5

238

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.

Unmade answered 27/9, 2011 at 6:3 Comment(3)
all the answers to your question so far explained a way to rewrite your server code so you ajax will work. None of them is about bypassing, as you asked specifically in your question. Did you find anyway to actually bypass this header? I really doubt that there would be one.Schlock
there is no way to baypass it. but you can put a file on your backend that performs the request. So you call per ajax the file on your own server, that file loads the data from retrieve.php and send them back to your javascript. In that case there are no CORS rules blocking you.Twice
The secure websocket protocol wss:// is not subject to CORS blocking.Crum
I
424

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://mcmap.net/q/17829/-how-does-the-39-access-control-allow-origin-39-header-work

Illogicality answered 27/9, 2011 at 6:12 Comment(9)
Thats rather unsafe. Check out my answer at the bottom.Achlamydeous
tnx, but you should not allow access to all origins as mentioned by @RobQuist in his comment, and in his answer provided a better approachIllogicality
So I found this page because I needed to actually 'bypass' Access Control on a server. The solution here isn't bypassing anything but simply properly configuring Access Control on his own server. In case anyone out there actually needs to bypass this they can use PHP's file_get_contents($remote_url);. There are obviously many ways to do this but this is how I did it.Aqueduct
@ShawnWhinnery that is basically the act of "proxying". Good solution if you really want to dynamically load data from another website that you have no control of.Achlamydeous
what exactly didnt work @jairhumberto any errors on the browser console? or on the server end? how does your code look like?Illogicality
nope, nothing. just nothing happens as if the code wasnt even there. I just try to make an ajax request to another domain file that has as the first line the header setted via header functionStride
wanted to run PHP script from dotnet core - moved php script to my other URL but was getting cross-site scripting error. added the code you showed to top of PHP and worked perfectly. Thanks!Bodleian
This is a poor practice, and leaves you wide open for cross site scripting. You pretty much only want your own domain allowed by default. The answer you really want is this: header('Access-Control-Allow-Origin: ' . 'http' . ( ( array_key_exists( 'HTTPS', $_SERVER ) && $_SERVER['HTTPS'] && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) ? 's' : null ) . '://' . $_SERVER['HTTP_HOST'] );Polack
What this does, is allow your own domain, and honors the current SSL settings on your server. If you want to add access for additional domains, just add another Access-Control-Allow-Origin header for each additional domain.Polack
C
46

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");
}
Cleodell answered 10/1, 2017 at 12:0 Comment(3)
This is an even better solution that the one I posted.Achlamydeous
HTTP_ORIGIN is not reliable, see #41231616Scorecard
I would suggest adding header('Vary: Origin'); into the if statement to let caches know that this route may return a different response for different referrals.Quirt
C
6

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.

Craver answered 18/3, 2012 at 22:18 Comment(0)
P
3

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.

Polack answered 23/4, 2018 at 1:10 Comment(0)
R
0

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

Rawls answered 27/9, 2011 at 6:7 Comment(1)
It is an HTTP header that your server sends to inform the browser that it is okay to reveal the result to the calling script despite the fact that the script’s origin domain does not match the server’s domain. Read up on Cross-Origin Resource Sharing!Rawls

© 2022 - 2024 — McMap. All rights reserved.