Skip to content

Instantly share code, notes, and snippets.

@zefer
Created September 28, 2010 14:25
Show Gist options
  • Save zefer/601076 to your computer and use it in GitHub Desktop.
Save zefer/601076 to your computer and use it in GitHub Desktop.
<cffunction name="allowCrossDomainAccess" returnType="void" access="public">
<cfset var stHeaders = getHttpRequestData().headers />
<cfif structKeyExists( stHeaders, "Origin" ) and cgi.request_method eq "OPTIONS">
<!---
Preflighted requests:
1. browser tells us it wants to make a non-basic x-domain request. Non-basic could mean it is a PUT, or contains custom headers, or a different content-type
2. based on what the browser tells us it wants to do, we respond and tell it what x-domain requests we allow
--->
<!--- x-domain requests from this host are allowed: * = any host allowed --->
<cfheader name="Access-Control-Allow-Origin" value="*" />
<!--- which http methods are allowed --->
<cfheader name="Access-Control-Allow-Methods" value="GET, POST, ACCEPT, OPTIONS" />
<!--- which custom headers are allowed --->
<cfheader name="Access-Control-Allow-Headers" value="X-Something-Custom, X-Something-Else" />
<!--- the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request. 1728000 seconds is 20 days --->
<cfheader name="Access-Control-Max-Age" value="1728000" />
<!--- allow cookies? NB: when enabled, wildcard Access-Control-Allow-Origin is not allowed --->
<!--- <cfheader name="Access-Control-Allow-Credentials" value="true" /> --->
<!--- no further messing, just respond with these headers - the browser will cache these 'permissions' and immediately follow-up with the original request --->
<cfcontent type="text/plain" reset="true" />
<cfabort />
<cfelseif listFindNoCase("GET,POST", cgi.request_method)>
<!---
Simple GET requests:
When the request is GET or POST, and no custom headers are sent, then no preflight check is required.
The browser accepts the response providing we allow it to with the Access-Control-Allow-Origin header
We allow any host to do simple x-domain GET requests
--->
<cfheader name="Access-Control-Allow-Origin" value="*" />
</cfif>
</cffunction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment