Firefox 3.5 implements the W3C Access Control specification.  As a result, Firefox 3.5 sends specific HTTP headers for cross-site requests initiated from withinXMLHttpRequest (which in Firefox 3.5 and beyond can be used to invoke different domains) and for cross-site font downloads.  It also expects to see specific HTTP headers sent back with cross-site responses.  An overview of these headers, including sample JavaScript code that initiates requests and processes responses from the server, as well as a discussion of each header, can be found here (HTTP Access Control).  The HTTP Access Control article should be read as a companion article to this one.  This article covers processing Access Control Requests and formulating Access Control Responses in PHP.  The target audience for this article are server programmers or administrators.  Although the code samples shown here are in PHP, similar concepts apply for ASP.net, Perl, Python, Java, etc.; in general, these concepts can be applied to any server-side programming environment that processes HTTP requests and dynamically formulates HTTP responses.

Discussion of HTTP headers

The article covering the HTTP headers used by both clients (such as Firefox 3.5 and beyond) 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 XMLHttpRequest such as Firefox 3.5 and above.

Simple cross-site requests

Simple Access Control Requests are initiated when:

  • An HTTP/1.1 GET or a POST is used as request method.  In the case of a POST, the Content-Type of the request body is one of application/x-www-form-urlencodedmultipart/form-data, or text/plain.
  • No custom headers are sent with the HTTP Request (such as X-Modified, etc.)

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

  • If the resource in question is meant to be widely accessed (just like any HTTP resource accessed by GET), than sending back the Access-Control-Allow-Origin: * header will be sufficient, unless the resource needs credentials such as Cookies and HTTP Authentication information.
  • If the resource should be kept restricted based on requester domain, OR if the resource needs to be accessed with credentials (or sets credentials), then filtering by the request's ORIGIN header may be necessary, or at least echoing back the requester's ORIGIN (e.g. Access-Control-Allow-Origin: http://arunranga.com).  Additionally, the Access-Control-Allow-Credentials: true header will have to be sent.  This is discussed in asubsequent section.

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 ORIGIN header sent by the browser (obtained through $_SERVER['HTTP_ORIGIN']) matches 'http://arunranga.com'.  If yes, it returns Access-Control-Allow-Origin: http://arunranga.com .  This example can be seen running here if you have a browser that implements Access Control (such as Firefox 3.5).

Preflighted requests

Preflighted Access Control Requests occur when:

  • A method other than GET or POST is used, or if POST is used with a Content-Type other than one of application/x-www-form-urlencoded,multipart/form-data, or text/plain.  For instance, if the Content-Type of the POST body is application/xml, a request is preflighted.
  • A custom header is (such as X-PINGARUNER) is sent with the request.

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:

  • Filtration based on ORIGIN, if any at all
  • Response to an OPTIONS request (which is the preflight request), including sending necessary values with Access-Control-Allow-MethodsAccess-Control-Allow-Headers (if any additional headers are needed in order for the application to work), and, if credentials are necessary for this resource,Access-Control-Allow-Credentials
  • Response to the actual request, including handling POST data, etc.

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 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 OPTIONS preflight as well as to the 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 POSTmethod, and header fields such as X-PINGARUNER can be sent with the actual request.  This example can be seen running here if you have a browser that implements Access Control (such as Firefox 3.5).

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, Firefox 3.5 (and above) will send the request with Cookies (e.g. if the withCredentials flag is set on  XMLHttpRequest).  If the server responds with 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")
{ // First See if There Is a Cookie
//$pageAccess = $_COOKIE['pageAccess'];
if (!isset($_COOKIE["pageAccess"])) { setcookie("pageAccess", 1, time()+2592000);
header('Access-Control-Allow-Origin: http://arunranga.com');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: text/plain');
echo 'I do not know you or anyone like you so I am going to mark you with a Cookie :-)'; }
else
{ $accesses = $_COOKIE['pageAccess'];
setcookie('pageAccess', ++$accesses, time()+2592000);
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');
echo 'Hello -- I know you or something a lot like you! You have been to ', $_SERVER['SERVER_NAME'], ' 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");
//exit(0);
}
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 if you have a browser that implements Access Control (such as Firefox 3.5).

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

https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control

Server-Side Access Control的更多相关文章

  1. 转:Oracle R12 多组织访问的控制 - MOAC(Multi-Org Access Control)

    什么是MOAC MOAC(Multi-Org Access Control)为多组织访问控制,是Oracle EBS R12的重要新功能,它可以实现在一个Responsibility下对多个Opera ...

  2. 【MongoDB】The Access control of mongodb

    In this blog we mainly talk about the access control including limitation of ip, setting listen port ...

  3. Oracle ACL(Access Control List)

    在oralce 11g中假如你想获取server的ip或者hostname,执行如下语句 SELECT utl_inaddr.get_host_address FROM dual;  //获取IP S ...

  4. Oracle Applications Multiple Organizations Access Control for Custom Code

    档 ID 420787.1 White Paper Oracle Applications Multiple Organizations Access Control for Custom Code ...

  5. Oracle R12 多组织访问的控制 - MOAC(Multi-Org Access Control)

    什么是MOAC MOAC(Multi-Org Access Control)为多组织访问控制,是Oracle EBS R12的重要新功能,它可以实现在一个Responsibility下对多个Opera ...

  6. Difference between ID and control.ClientID OR why use control.ClientID if I can access control through ID

     https://stackoverflow.com/questions/3743582/difference-between-id-and-control-clientid-or-why-use-c ...

  7. Browser security standards via access control

    A computing system is operable to contain a security module within an operating system. This securit ...

  8. Enhancing network controls in mandatory access control computing environments

    A Mandatory Access Control (MAC) aware firewall includes an extended rule set for MAC attributes, su ...

  9. Access control differentiation in trusted computer system

    A trusted computer system that offers Linux® compatibility and supports contemporary hardware speeds ...

随机推荐

  1. ArcGIS中文件共享锁定数据溢出 这个方法不行,建议用gdb,不要用mdb

    ArcGIS中文件共享锁定数据溢出 (2011-11-24 15:52:41) 转载▼ 标签: 杂谈 分类: GIS 文件共享锁定数溢出.(Error 3052)1. Access数据库,同时操作大量 ...

  2. iOS之苹果和百度地图的使用

    iOS中使用较多的3款地图,google地图.百度地图.苹果自带地图(高德).其中苹果自带地图在中国使用的是高德的数据.苹果在iOS 6之后放弃了使用谷歌地图,而改用自家的地图.在国内使用的较多的就是 ...

  3. Java ==,equals() 和hashCode

    Kruger上课讲到==和equals()方法是不同的,经过查询将具体内容整理一下,在查询过程中发现hashCode()方法与equlas()联系紧密,故一起研究. 比较浅显,以后如果理解更多随时更新 ...

  4. git设计哲学

    刚开始使用git的时候,总想拿git来和cvs或者svn来作对比,但不久后发现这个想法本身就是错的,git完全就是另外一种物种,一种本属于未来的物种.它的对象存储方式,快照,分支等,都是完全不同的. ...

  5. C#扫盲之:String字符串的常用方法和冷知识

    前言 字符串对于任何编程语言都是必须操作和了解的,因为在实际编程中,任何项目和工程都必须要处理字符串数据,文件路径.提示消息,文本的处理等等,而在使用过程中很多人都是没有系统的了解,大量使用strin ...

  6. Git之路--1

    昨天下午到今天早上,终于搞定了github.过程很难过,不过看到自己的github上有代码了.还是小小的开心了一下.暂时没时间分享相关技术,附带微博链接,有想试试上传上Github的小伙伴可以查看我的 ...

  7. VIM学习1

    不得不说鸟哥的Linux写得太好了,VIM篇章,通读一篇,感觉收获挺大.之前几年前装逼硬着学,感觉硬是没懂,看的特晕,学得特别慢,抄一两遍也没什么多大的作用.这一回看了,感觉马上就能记住不少,当然大多 ...

  8. ACM——线性表操作

    线性表操作 时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte总提交:2795            测试通过:589 描述 线性表是n个元素 ...

  9. ns2出现Client: Handoff Attempt的情况解决

    找到mac/mac-802_11.cc,这是系统本身一个bug,对于adhoc网络无需进行切换尝试. > if (*rcount == 3 && handoff == 0) {& ...

  10. Android在onCreate()中获得控件尺寸

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceSt ...