--- title: Server-Side Access Control (CORS) slug: Web/HTTP/Server-Side_Access_Control translation_of: Web/HTTP/CORS translation_of_original: Web/HTTP/Server-Side_Access_Control ---

Системы контроля доступа производят идентификацию авторизацииаутентификацию, подтверждение доступа и подотчетность сущностей с помощью учетных данных для входа, включая пароль, личный идентификационный номер (PINs), биометрическое сканирование и физический или электронный ключ.

Контроль доступа --- это техника безопасности, которую можно использовать для регулирования процессом того, кто или что может видеть или использовать ресурсы в вычислительном окружении.

{{HTTPSidebar}}

Для меж-сайтовых запросов, произведенных с помощью {{domxref("XMLHttpRequest")}} или Fetch API, браузеры передают специальные HTTP заголовки. Так же ожидаемо увидеть определенные HTTP заголовки, переданные обратно внутри меж-сайтового ответа. Обзор этих заголовков, включая примеры JavaScript кода, создающего запросы и обрабатывающего ответы от сервера, как и описание каждого из заголовков, может быть найден в статье HTTP Access Control (CORS) и должен быть прочитан вместе с данной. Эта статья покрывает обработку Запросов контроля доступа и формулировку Ответов контроля доступа в PHP. Целевая аудитория для этой статьи ---  разработчики серверов и администраторы. Хотя примеры кода, приведенные тут, на PHP, подобная концепция применяется в ASP.net, Perl, Python, Java, etc.; в общем, эти концепции могут быть применены в любом сервером окружении, который обрабатывает HTTP запросы и динамически формирует HTTP ответы.

Discussion of HTTP headers

The article covering the HTTP headers used by both clients and servers is here, and should be considered prerequisite reading.

Working code samples

The PHP snippets (and the JavaScript invocations to the server) in subsequent sections are taken from the working code samples posted here. These will work in browsers that implement cross-site {{domxref("XMLHttpRequest")}}.

Simple cross-site requests

Simple Access Control Requests are initiated when:

In this case, responses can be sent back based on some considerations.

The section on Simple Access Control Requests shows you the header exchanges between client and server. Here is a PHP code segment that handles a Simple Request:

<?php

// We'll be granting access to only the arunranga.com domain
// which we think is safe to access this resource as application/xml

if($_SERVER['HTTP_ORIGIN'] == "http://arunranga.com") {
    header('Access-Control-Allow-Origin: http://arunranga.com');
    header('Content-type: application/xml');
    readfile('arunerDotNetResource.xml');
} else {
  header('Content-Type: text/html');
  echo "<html>";
  echo "<head>";
  echo "   <title>Another Resource</title>";
  echo "</head>";
  echo "<body>",
       "<p>This resource behaves two-fold:";
  echo "<ul>",
         "<li>If accessed from <code>http://arunranga.com</code> it returns an XML document</li>";
  echo   "<li>If accessed from any other origin including from simply typing in the URL into the browser's address bar,";
  echo   "you get this HTML document</li>",
       "</ul>",
     "</body>",
   "</html>";
}
?>

The above checks to see if the {{HTTPHeader("Origin")}} header sent by the browser (obtained through $_SERVER['HTTP_ORIGIN']) matches 'http://arunranga.com'. If yes, it returns {{HTTPHeader("Access-Control-Allow-Origin")}}: http://arunranga.com. This example can be seen running here.

Preflighted requests

Preflighted Access Control Requests occur when:

The section on Preflighted Access Control Requests shows a header exchange between client and server. A server resource responding to a preflight requests needs to be able to make the following determinations:

Here is an example in PHP of handling a preflighted request:

<?php

if($_SERVER['REQUEST_METHOD'] == "GET") {

  header('Content-Type: text/plain');
  echo "This HTTP resource is designed to handle POSTed XML input";
  echo "from arunranga.com and not be retrieved with GET";

} elseif($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
  // Tell the Client we support invocations from arunranga.com and
  // that this preflight holds good for only 20 days

  if($_SERVER['HTTP_ORIGIN'] == "http://arunranga.com") {
    header('Access-Control-Allow-Origin: http://arunranga.com');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Allow-Headers: X-PINGARUNER');
    header('Access-Control-Max-Age: 1728000');
    header("Content-Length: 0");
    header("Content-Type: text/plain");
    //exit(0);
  } else {
    header("HTTP/1.1 403 Access Forbidden");
    header("Content-Type: text/plain");
    echo "You cannot repeat this request";
  }

} elseif($_SERVER['REQUEST_METHOD'] == "POST") {
  // Handle POST by first getting the XML POST blob,
  // and then doing something to it, and then sending results to the client

  if($_SERVER['HTTP_ORIGIN'] == "http://arunranga.com") {
    $postData = file_get_contents('php://input');
    $document = simplexml_load_string($postData);

    // do something with POST data

    $ping = $_SERVER['HTTP_X_PINGARUNER'];

    header('Access-Control-Allow-Origin: http://arunranga.com');
    header('Content-Type: text/plain');
    echo // some string response after processing
  } else {
    die("POSTing Only Allowed from arunranga.com");
  }
} else {
    die("No Other Methods Allowed");
}
?>

Note the appropriate headers being sent back in response to the {{HTTPMethod("OPTIONS")}} preflight as well as to the {{HTTPMethod("POST")}} data. One resource thus handles the preflight as well as the actual request. In the response to the OPTIONS request, the server notifies the client that the actual request can indeed be made with the POST method, and header fields such as X-PINGARUNER can be sent with the actual request. This example can be seen running here.

Credentialed requests

Credentialed Access Control Requests – that is, requests that are accompanied by Cookies or HTTP Authentication information (and which expect Cookies to be sent with responses) – can be either Simple or Preflighted, depending on the request methods used.

In a Simple Request scenario, the request will be sent with Cookies (e.g. if the withCredentials flag is set on {{domxref("XMLHttpRequest")}}). If the server responds with {{HTTPHeader("Access-Control-Allow-Credentials")}}: true attached to the credentialed response, then the response is accepted by the client and exposed to web content. In a Preflighted Request, the server can respond with Access-Control-Allow-Credentials: true to the OPTIONS request.

Here is some PHP that handles credentialed requests:

<?php

if($_SERVER['REQUEST_METHOD'] == "GET") {
  header('Access-Control-Allow-Origin: http://arunranga.com');
  header('Access-Control-Allow-Credentials: true');
  header('Cache-Control: no-cache');
  header('Pragma: no-cache');
  header('Content-Type: text/plain');

  // First See if There Is a Cookie
  if (!isset($_COOKIE["pageAccess"])) {
    setcookie("pageAccess", 1, time()+2592000);
    echo 'I do not know you or anyone like you so I am going to';
    echo 'mark you with a Cookie :-)';
  } else {
    $accesses = $_COOKIE['pageAccess'];
    setcookie('pageAccess', ++$accesses, time()+2592000);
    echo 'Hello -- I know you or something a lot like you!';
    echo 'You have been to ', $_SERVER['SERVER_NAME'], ';
    echo 'at least ', $accesses-1, ' time(s) before!';
  }
} elseif($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
  // Tell the Client this preflight holds good for only 20 days
  if($_SERVER['HTTP_ORIGIN'] == "http://arunranga.com") {
    header('Access-Control-Allow-Origin: http://arunranga.com');
    header('Access-Control-Allow-Methods: GET, OPTIONS');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 1728000');
    header("Content-Length: 0");
    header("Content-Type: text/plain");
  } else {
    header("HTTP/1.1 403 Access Forbidden");
    header("Content-Type: text/plain");
    echo "You cannot repeat this request";
  }
} else {
  die("This HTTP Resource can ONLY be accessed with GET or OPTIONS");
}
?>

Note that in the case of credentialed requests, the Access-Control-Allow-Origin: header must not have a wildcard value of "*".  It must mention a valid origin domain. The example above can be seen running here.

Apache examples

Restrict access to certain URIs

One helpful trick is to use an Apache rewrite, environment variable, and headers to apply Access-Control-Allow-* to certain URIs. This is useful, for example, to constrain cross-origin requests to GET /api(.*).json requests without credentials:

RewriteRule ^/api(.*)\.json$ /api$1.json [CORS=True]
Header set Access-Control-Allow-Origin "*" env=CORS
Header set Access-Control-Allow-Methods "GET" env=CORS
Header set Access-Control-Allow-Credentials "false" env=CORS

See also