0

I have a website called "example.com". I have a PHP file on example.com that I make .ajax() requests to. I want to prevent other sites from making requests to this file. I'm setting Access-Control-Allow-Origin in this PHP file to do so. Here is my code

<?php

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

    if(isset($_POST["request"]){

        echo "Request Successful";

    }

?>

Can this approach be exploited? Is setting this header preventing other sites from making ajax requests to the PHP file? Thanks in advance for your help.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Preston Guillot Jul 13 '20 at 00:05
  • Other sites can't make ajax requests to your domain by default - this is the standard single origin policy all browsers respect. You need to use the CORS headers if you want to _enable_ cross origin requests. – Preston Guillot Jul 13 '20 at 00:09
  • Thanks Preston, good to know. So to confirm, I don't need to add any extra security features to prevent other websites from making ajax requests to my PHP file? – Pat Pistachio Jul 13 '20 at 00:16
  • Right, they're blocked by default. – Barmar Jul 13 '20 at 00:34
  • Why don't you simply test it? Write a bit of JS code and run it on your localhost. Try to access the functionality. See in web console if it succeeds. – Marek Puchalski Jul 13 '20 at 04:44
  • @PatPistachio To be clear, single origin policy is a _client side_ security feature of browsers - no modern browser, by default, will allow a script loaded from site A to issue a request to site B unless site B presents the correct CORS headers. That said, this does _not_ protect site B from malicious intent. If your goal is to ensure your _server_ doesn't respond to unexpected requests, you need an appropriate authorization scheme in place for the API. – Preston Guillot Jul 14 '20 at 14:23

0 Answers0