{"id":3908,"date":"2016-11-07T00:33:54","date_gmt":"2016-11-07T06:33:54","guid":{"rendered":"https:\/\/weblizar.com\/?p=3908"},"modified":"2025-08-07T15:41:06","modified_gmt":"2025-08-07T10:11:06","slug":"enable-cross-origin-resource-sharing","status":"publish","type":"post","link":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/","title":{"rendered":"Enable Cross-Origin Resource Sharing"},"content":{"rendered":"<h3><strong>What is Cross-Origin Resource Sharing (CORS) &#8211;<\/strong><\/h3>\n<p>Cross-origin resource sharing is fundamental that can make visible the resources\u00a0which are hidden. Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain boundaries. <span id=\"invisible-marker-before\"><\/span>CORS allows web scripts to interact more openly with content outside of the original domain, leading to better integration between web services.\u00a0Cross-origin resource sharing allows blocked resources just like &#8211; fonts, on a web page to be requested from another domain outside the domain from which the resource originated.<\/p>\n<p>CORS defines a way in which a browser and server can interact to determine whether or not it is safe to allow the cross-origin request. It allows for more freedom and functionality than purely same-origin requests but is more secure than simply allowing all cross-origin requests.<\/p>\n<p>&nbsp;<\/p>\n<h2>Why is CORS important?<\/h2>\n<p>JavaScript and the web programming has grown by leaps and bounds over the years, but the same-origin policy still remains. This prevents JavaScript from making requests across domain boundaries and has spawned various hacks for making cross-domain requests.<\/p>\n<p>CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed. CORS continues the spirit of the open web by bringing API access to all.<\/p>\n<h3><strong>Enable Cross-Origin Resource Sharing &#8211; <\/strong><\/h3>\n<h3><span style=\"color: #008000;\">1. CORS on Apache<\/span><\/h3>\n<p>To add the CORS authorization to the header using Apache, simply add the following line inside either the <strong><code>&lt;Directory&gt;<\/code><\/strong>,<strong><code>&lt;Location&gt;<\/code><\/strong><strong> <code>&lt;Files&gt;<\/code> or <code>&lt;VirtualHost&gt;<\/code><\/strong> sections of your server config (usually located in a *.conf files, such as httpd.conf or apache.conf), or within a <code>.htaccess<\/code> file:<\/p>\n<blockquote>\n<pre class=\"code\"> Header set Access-Control-Allow-Origin \"*\"<\/pre>\n<\/blockquote>\n<p>To ensure that your changes are correct, it is strongly recommended that you use<\/p>\n<blockquote>\n<pre class=\"code\">apachectl -t<\/pre>\n<\/blockquote>\n<p>to check your configuration changes for errors. After this passes, you may need to reload Apache to make sure your changes are applied by running the command<\/p>\n<blockquote>\n<pre>sudo service apache2 reload<\/pre>\n<\/blockquote>\n<p>or<\/p>\n<blockquote>\n<pre>apachectl -k graceful<\/pre>\n<\/blockquote>\n<p>Altering headers requires the use of <a href=\"https:\/\/httpd.apache.org\/docs\/2.0\/mod\/mod_headers.html\">mod_headers<\/a>. Mod_headers is enabled by default in Apache, however, you may want to ensure it&#8217;s enabled by run<\/p>\n<blockquote>\n<pre>a2enmod headers<\/pre>\n<\/blockquote>\n<p><span style=\"color: #ff0000;\">Note<\/span>: you can also use <span style=\"color: #ff0000;\"><code>add<\/code> <\/span>rather than <span style=\"color: #ff0000;\"><code>set<\/code><\/span>, but be aware that <span style=\"color: #ff0000;\"><code>add<\/code> <\/span>can add the header multiple times, so it&#8217;s likely safer to use set.<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">2. CORS on App Engine<\/span><\/h3>\n<p>For Python-based applications in Google App Engine, the <code>self.response.headers.add_header()<\/code> method can be used, such as:<\/p>\n<blockquote>\n<pre class=\"code\">class CORSEnabledHandler(webapp.RequestHandler):\r\n  def get(self):\r\n    self.response.headers.add_header(\"Access-Control-Allow-Origin\", \"*\")\r\n    self.response.headers['Content-Type'] = 'text\/csv'\r\n    self.response.out.write(self.dump_csv())<\/pre>\n<\/blockquote>\n<p>For Java-based applications, use <code>resp.addHeader()<\/code>:<\/p>\n<blockquote>\n<pre class=\"code\">public void doGet(HttpServletRequest req, HttpServletResponse resp) {\r\n  resp.addHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n  resp.addHeader(\"Content-Type\", \"text\/csv\");\r\n  resp.getWriter().append(csvString);\r\n}<\/pre>\n<\/blockquote>\n<p>And for Go-based applications, use <code>w.Header().Add()<\/code>:<\/p>\n<blockquote>\n<pre class=\"code\">func doGet(w http.ResponseWriter, r *http.Request) {\r\n  w.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\r\n  w.Header().Add(\"Content-Type\", \"text\/csv\")\r\n  fmt.Fprintf(w, csvData)\r\n}\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">3. CORS on ASP.NET<\/span><\/h3>\n<p>If you don&#8217;t have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:<\/p>\n<blockquote>\n<pre class=\"code\">Response.AppendHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n\r\n<\/pre>\n<\/blockquote>\n<h4>ASP.NET Web API<\/h4>\n<p>ASP.NET Web API 2 supports CORS.<\/p>\n<p>To enable CORS support, add the <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.AspNet.WebApi.Cors\">Microsoft.AspNet.WebApi.Cors<\/a> NuGet packages to your project.<\/p>\n<p>Add this code to your configuration:<\/p>\n<blockquote>\n<pre class=\"code\">public static void Register(HttpConfiguration config)\r\n{\r\n    \/\/ New code\r\n    config.EnableCors();\r\n}<\/pre>\n<\/blockquote>\n<p>To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller or controller method:<\/p>\n<blockquote>\n<pre class=\"code\">[EnableCors(origins: \"http:\/\/example.com\", headers: \"*\", methods: \"*\")]\r\npublic class TestController : ApiController\r\n{\r\n    \/\/ Controller methods not shown...\r\n}\r\n\r\n<\/pre>\n<\/blockquote>\n<h3>Enabling Globally<\/h3>\n<p>The method described above can also be used to enable CORS across the API without annotating each controller:<\/p>\n<blockquote>\n<pre class=\"code\">public static void Register(HttpConfiguration config)\r\n{\r\n    var corsAttr = new EnableCorsAttribute(\"http:\/\/example.com\", \"*\", \"*\");\r\n    config.EnableCors(corsAttr);\r\n}\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">4. CORS on AWS API Gateway<\/span><\/h3>\n<p>Amazon API Gateway adds support for CORS enabling through a simple button in the API Gateway console. Unfortunately, that button has a partial behavior, thus setting CORS correctly only for 200 answers (so not other HTTP status codes) and ignoring Jquery header support. The best solution considered so far is about avoiding to use the CORS button and set configurations manually.<\/p>\n<h4><strong>This can be achieved in a couple of steps:<\/strong><\/h4>\n<p>1. Log into API Gateway console<\/p>\n<p>2. Create all the REST resources that need to be exposed with their methods before setting up CORS (if new resources\/methods are created after enabling CORS, these steps must be repeated)<\/p>\n<p>3. Select a resource<\/p>\n<p>4. Add OPTIONS method, choose as integration type &#8220;mock&#8221;<\/p>\n<p>5. For each Method of a resource<\/p>\n<p>6. Go to Response Method<\/p>\n<p>7. Add all the response method that should be supported (i.e. 200, 500, etc.)<\/p>\n<p>8. For each response code set Response Headers to<br \/>\nX-Requested-With<br \/>\nAccess-Control-Allow-Headers<br \/>\nAccess-Control-Allow-Origin<br \/>\nAccess-Control-Allow-Methods<\/p>\n<p>9. Go to Integration Response, select one of the created response codes, then Header Mappings<\/p>\n<p>10. Insert default values for headers<br \/>\nexample:<br \/>\nX-Requested-With: &#8216;*&#8217;<br \/>\nAccess-Control-Allow-Headers: &#8216;Content-Type,X-Amz-Date,Authorization,X-API-Key,x-requested-with&#8217;<br \/>\nAccess-Control-Allow-Origin: &#8216;*&#8217;<br \/>\nAccess-Control-Allow-Methods: &#8216;POST,GET,OPTIONS&#8217;<br \/>\nThis operation has to be repeated for each method, including the newly created OPTIONS<\/p>\n<p>11. Deploy the API to a stage<\/p>\n<p>12. Check using http:\/\/client.cors-api.appspot.com\/client that CORS requests have been successfully enabled<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">5. CORS on Caddyserver<\/span><\/h3>\n<p>To add the CORS authorization to the header using Caddy, simply add the following line inside your caddyfile:<\/p>\n<blockquote>\n<pre class=\"code\">cors\r\n\r\n<\/pre>\n<\/blockquote>\n<p>This will allow <span style=\"color: #ff0000;\"><b>all<\/b><\/span> resources to be accessed from <span style=\"color: #ff0000;\"><b>every<\/b><\/span> domain.<\/p>\n<p>You can also be more specific, i.e. allow specific resources to specific domains:<\/p>\n<blockquote>\n<pre class=\"code\">cors \/foo http:\/\/mysite.com http:\/\/anothertrustedsite.com<\/pre>\n<\/blockquote>\n<p>There are many more options you can use, here is a full example, as shown in the <a href=\"http:\/\/web.archive.org\/web\/20160806141032\/https:\/\/caddyserver.com\/docs\/cors\" target=\"_blank\" rel=\"noopener\">caddyserver docs<\/a>:<\/p>\n<blockquote>\n<pre class=\"code\">cors \/ {\r\n  origin            http:\/\/allowedSite.com\r\n  origin            http:\/\/anotherSite.org https:\/\/anotherSite.org\r\n  methods           POST,PUT\r\n  allow_credentials false\r\n  max_age           3600\r\n  allowed_headers   X-Custom-Header,X-Foobar\r\n  exposed_headers   X-Something-Special,SomethingElse\r\n}\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">6. CORS in CGI Scripts<\/span><\/h3>\n<p>Just output the line:<\/p>\n<blockquote>\n<pre class=\"code\">Access-Control-Allow-Origin: *<\/pre>\n<\/blockquote>\n<p>.. as part of your CGI script&#8217;s headers, for example, in Perl (using CGI.pm):<\/p>\n<blockquote>\n<pre class=\"code\">print header(\r\n  -type =&gt; 'text\/turtle',\r\n  -content_location =&gt; 'mydata.ttl',\r\n  -access_control_allow_origin =&gt; '*',\r\n);\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">7. CORS in Perl PSGI scripts<\/span><\/h3>\n<p>The module Plack::Middleware::CrossOrigin provides a complete CORS server side implementation. To allow any request from any location, just add this to your builder:<\/p>\n<blockquote>\n<pre class=\"code\">enable 'CrossOrigin', origins =&gt; '*';\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">8. CORS in Python<\/span><\/h3>\n<blockquote>\n<pre class=\"code\">print \"Content-Type: text\/turtle\"\r\nprint \"Content-Location: mydata.ttl\"\r\nprint \"Access-Control-Allow-Origin: *\"\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">9. CORS on ExpressJS<\/span><\/h3>\n<p>In your <a href=\"https:\/\/expressjs.com\/\">ExpressJS<\/a> app on <a href=\"https:\/\/nodejs.org\/en\">node.js<\/a>, do the following with your routes:<\/p>\n<blockquote>\n<pre class=\"code\">app.use(function(req, res, next) {\r\n  res.header(\"Access-Control-Allow-Origin\", \"*\");\r\n  res.header(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\");\r\n  next();\r\n});\r\n\r\napp.get('\/', function(req, res, next) {\r\n  \/\/ Handle the get for this route\r\n});\r\n\r\napp.post('\/', function(req, res, next) {\r\n \/\/ Handle the post for this route\r\n});\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">10. CORS on IIS6<\/span><\/h3>\n<p>To CORS-enable Microsoft IIS6, perform the following steps:<\/p>\n<ol>\n<li>Open <em>Internet Information Service (IIS)<\/em> Manager<\/li>\n<li>Right-click the site you want to enable CORS for and go to <em>Properties<\/em><\/li>\n<li>Change to the <em>HTTP Headers<\/em> tab<\/li>\n<li>In the <em>Custom HTTP headers<\/em> section, click <em>Add<\/em><\/li>\n<li>Enter <code>Access-Control-Allow-Origin<\/code> as the header name<\/li>\n<li>Enter <code>*<\/code> as the header value<\/li>\n<li>Click <em>Ok<\/em> twice<\/li>\n<\/ol>\n<h3><span style=\"color: #008000;\">11. CORS on IIS7<\/span><\/h3>\n<p>For Microsoft IIS7, merge this into the <code>web.config<\/code> file at the root of your application or site:<\/p>\n<blockquote>\n<pre class=\"code\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;configuration&gt;\r\n &lt;system.webServer&gt;\r\n   &lt;httpProtocol&gt;\r\n     &lt;customHeaders&gt;\r\n       &lt;add name=\"Access-Control-Allow-Origin\" value=\"*\" \/&gt;\r\n     &lt;\/customHeaders&gt;\r\n   &lt;\/httpProtocol&gt;\r\n &lt;\/system.webServer&gt;\r\n&lt;\/configuration&gt;<\/pre>\n<\/blockquote>\n<p>If you don&#8217;t have a <code>web.config<\/code> file already, or don&#8217;t know what one is, just create a new file called <code>web.config<\/code> containing the snippet above.<\/p>\n<h3><span style=\"color: #008000;\">12. CORS on Meteor<\/span><\/h3>\n<p>To add CORS authorization to a <a href=\"https:\/\/www.meteor.com\/\">Meteor<\/a> application, use the <a href=\"https:\/\/docs.meteor.com\/#\/full\/webapp\">webapp<\/a> package&#8217;s <code>WebApp.connectHandlers<\/code> to customize HTTP headers.<\/p>\n<blockquote>\n<pre class=\"code\">\/\/ Listen to incoming HTTP requests, can only be used on the server\r\nWebApp.rawConnectHandlers.use(function(req, res, next) {\r\n  res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n  return next();\r\n});<\/pre>\n<\/blockquote>\n<p>Use the optional <code>path<\/code> argument to only call the handler for paths that match a specified string.<\/p>\n<blockquote>\n<pre class=\"code\">\/\/ Listen to incoming HTTP requests, can only be used on the server\r\nWebApp.rawConnectHandlers.use(\"\/public\", function(req, res, next) {\r\n  res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n  return next();\r\n});\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">13. CORS on Nginx<\/span><\/h3>\n<p>The following Nginx configuration enables CORS, with support for preflight requests.<\/p>\n<blockquote>\n<pre class=\"code\">#\r\n# Wide-open CORS config for nginx\r\n#\r\nlocation \/ {\r\n     if ($request_method = 'OPTIONS') {\r\n        add_header 'Access-Control-Allow-Origin' '*';\r\n        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';\r\n        #\r\n        # Custom headers and headers various browsers *should* be OK with but aren't\r\n        #\r\n        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';\r\n        #\r\n        # Tell client that this pre-flight info is valid for 20 days\r\n        #\r\n        add_header 'Access-Control-Max-Age' 1728000;\r\n        add_header 'Content-Type' 'text\/plain charset=UTF-8';\r\n        add_header 'Content-Length' 0;\r\n        return 204;\r\n     }\r\n     if ($request_method = 'POST') {\r\n        add_header 'Access-Control-Allow-Origin' '*';\r\n        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';\r\n        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';\r\n     }\r\n     if ($request_method = 'GET') {\r\n        add_header 'Access-Control-Allow-Origin' '*';\r\n        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';\r\n        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';\r\n     }\r\n}\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">14. CORS in Perl PSGI scripts<\/span><\/h3>\n<p>The module <a href=\"https:\/\/metacpan.org\/module\/Plack::Middleware::CrossOrigin\">Plack::Middleware::CrossOrigin<\/a> provides a complete CORS server side implementation. To allow any request from any location, just add this to your builder:<\/p>\n<blockquote>\n<pre class=\"code\">enable 'CrossOrigin', origins =&gt; '*';<\/pre>\n<\/blockquote>\n<p>This module is also available in Debian and Ubuntu as libplack-middleware-crossorigin-perl.<\/p>\n<h3><span style=\"color: #008000;\">15. CORS on PHP<\/span><\/h3>\n<p>If you don&#8217;t have access to configure Apache, you can still send the header from a PHP script. It&#8217;s a case of adding the following to your PHP scripts:<\/p>\n<blockquote>\n<pre class=\"code\">&lt;?php\r\n header(\"Access-Control-Allow-Origin: *\");<\/pre>\n<\/blockquote>\n<p><span style=\"color: #ff0000;\">Note:<\/span> as with all uses of the PHP <a href=\"https:\/\/www.php.net\/manual\/en\/function.header.php\">header function<\/a>, this must be before any output has been sent from the server.<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">16. CORS on ColdFusion<\/span><\/h3>\n<p>If you don&#8217;t have access to configure you web server, you can still send the header from a Coldfusion script. It&#8217;s a case of adding the following to your Coldfusion scripts:<\/p>\n<h4>Tag Based File<\/h4>\n<blockquote>\n<pre class=\"code\">&lt;cfheader name=\"Access-Control-Allow-Origin\" value=\"*\"&gt;\r\n\r\n<\/pre>\n<\/blockquote>\n<h4>Script Based File<\/h4>\n<blockquote>\n<pre class=\"code\">var response = getPageContext().getResponse();\r\nresponse.setHeader(\"Access-Control-Allow-Origin\",\"*\");<\/pre>\n<\/blockquote>\n<p><span style=\"color: #ff0000;\">Note:<\/span> This needs to be set before any output has been sent from the server.<\/p>\n<h3><span style=\"color: #008000;\">17. CORS on Tomcat<\/span><\/h3>\n<p>Apache Tomcat includes support for CORS (Starting from Tomcat version 7.0.41).<\/p>\n<p>Here is an example from those docs that demonstrates a minimal CORS configuration:<\/p>\n<blockquote>\n<pre class=\"code\">&lt;filter&gt;\r\n  &lt;filter-name&gt;CorsFilter&lt;\/filter-name&gt;\r\n  &lt;filter-class&gt;org.apache.catalina.filters.CorsFilter&lt;\/filter-class&gt;\r\n&lt;\/filter&gt;\r\n&lt;filter-mapping&gt;\r\n  &lt;filter-name&gt;CorsFilter&lt;\/filter-name&gt;\r\n  &lt;url-pattern&gt;\/*&lt;\/url-pattern&gt;\r\n&lt;\/filter-mapping&gt;\r\n\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">18. CORS on Virtuoso<\/span><\/h3>\n<p>These instance\/server-level settings require OpenLink <a href=\"https:\/\/vos.openlinksw.com\/owiki\/wiki\/VOS\/VOSNews\">Virtuoso Open Source (VOS) 6.1.3<\/a> or later.<\/p>\n<ol>\n<li>In the <em>Virtuoso Conductor<\/em>, go to <em>Web Application Server<\/em> \u2192 <em>Virtual Domains &amp; Directories<\/em>.<\/li>\n<li>Expand the default <em>Interface<\/em> store.<\/li>\n<li>Click <em>New Directory<\/em>.<\/li>\n<li>Specify the desired <em>Virtual Directory Type<\/em>, or choose an existing virtual directory to use as a template.<\/li>\n<li>Click <em>Next<\/em>.<\/li>\n<li>Specify the <em>Directory Path<\/em> value.<\/li>\n<li>Set the <em>CORS options<\/em>.\n<ul>\n<li><em>Cross-Origin Resource Sharing<\/em> &#8211; contains a single wildcard asterisk, i.e., <code>*<\/code> or an origin, such as or<code>http:\/\/example.com:8080<\/code> <code>http:\/\/foo.example.com<\/code>. Scripts are authorized to retrieve a resource if that resource either uses the wildcard or lists the origin of the script. For this example, enter the following single URI: <code><a href=\"http:\/\/demo.openlinksw.com\/\">http:\/\/demo.openlinksw.com<\/a><\/code><\/li>\n<li><em>Reject Unintended CORS<\/em> check-box &#8211; when ticked and the application does not overwrite headers, unmatched Origins will be rejected by sending an empty response.<\/li>\n<\/ul>\n<\/li>\n<li>Click <em>Save changes<\/em>.<\/li>\n<\/ol>\n<p>For older versions of Virtuoso, any of the Web Application-level instructions below may be used. Any Virtuoso-based application can implement CORS checking through well-known HTTP functions <a href=\"https:\/\/docs.openlinksw.com\/virtuoso\/fn_http_request_header\/\">http_request_header()<\/a> and <a href=\"https:\/\/docs.openlinksw.com\/virtuoso\/fn_http_header\/\">http_header()<\/a>, for example:<\/p>\n<blockquote>\n<pre class=\"code\">&lt;?vsp\r\nIF (http_request_header (lines, 'Origin', NULL) = 'http:\/\/host.org')\r\n{\r\n  http_header ('Access-Control-Allow-Origin: http:\/\/host.org\\r\\n');\r\n}\r\nELSE\r\n{\r\n  RETURN;\r\n}\r\n-- Additional code here ---\r\n?&gt;\r\n<\/pre>\n<\/blockquote>\n<h3><span style=\"color: #008000;\">19. CORS on WCF<\/span><\/h3>\n<p>For WCF service you have to develop new behavior and include it in the endpoint configuration:<\/p>\n<h5>Create Message Inspector<\/h5>\n<blockquote>\n<pre class=\"code\"> public class CustomHeaderMessageInspector : IDispatchMessageInspector\r\n            {\r\n                Dictionary&lt;string, string&gt; requiredHeaders;\r\n                public CustomHeaderMessageInspector (Dictionary&lt;string, string&gt; headers)\r\n                {\r\n                    requiredHeaders = headers ?? new Dictionary&lt;string, string&gt;();\r\n                }\r\n\r\n                public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)\r\n                {\r\n                    var httpHeader = reply.Properties[\"httpResponse\"] as HttpResponseMessageProperty;\r\n                    foreach (var item in requiredHeaders)\r\n                    {\r\n                        httpHeader.Headers.Add(item.Key, item.Value);\r\n                    }           \r\n                }\r\n            }\r\n\r\n<\/pre>\n<\/blockquote>\n<p>Create Endpoint Behavior and use Message Inspector to add headers<\/p>\n<blockquote>\n<pre class=\"code\">  public class EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior\r\n            {\r\n                public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)\r\n                {\r\n           \r\n                }\r\n\r\n                public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)\r\n                {\r\n            \r\n                }\r\n\r\n                public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)\r\n                {\r\n                    var requiredHeaders = new Dictionary&lt;string, string&gt;();\r\n\r\n                    requiredHeaders.Add(\"Access-Control-Allow-Origin\", \"*\");\r\n                    requiredHeaders.Add(\"Access-Control-Request-Method\", \"POST,GET,PUT,DELETE,OPTIONS\");\r\n                    requiredHeaders.Add(\"Access-Control-Allow-Headers\", \"X-Requested-With,Content-Type\");\r\n\r\n                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));\r\n                }\r\n\r\n                public void Validate(ServiceEndpoint endpoint)\r\n                {\r\n            \r\n                }\r\n\r\n                public override Type BehaviorType\r\n                {\r\n                    get { return typeof(EnableCrossOriginResourceSharingBehavior); }\r\n                }\r\n\r\n                protected override object CreateBehavior()\r\n                {\r\n                    return new EnableCrossOriginResourceSharingBehavior();\r\n                }\r\n            }\r\n\r\n<\/pre>\n<\/blockquote>\n<p>Register new behavior in web.config<\/p>\n<blockquote>\n<pre class=\"code\">&lt;extensions&gt;\r\n              &lt;behaviorExtensions&gt;        \r\n                &lt;add name=\"crossOriginResourceSharingBehavior\" type=\"Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral\" \/&gt;        \r\n              &lt;\/behaviorExtensions&gt;      \r\n            &lt;\/extensions&gt;\r\n\r\n<\/pre>\n<\/blockquote>\n<p>Add new behavior to endpoint behavior configuration<\/p>\n<blockquote>\n<pre class=\"code\"> &lt;endpointBehaviors&gt;      \r\n            &lt;behavior name=\"jsonBehavior\"&gt;\r\n                &lt;webHttp \/&gt;\r\n                &lt;crossOriginResourceSharingBehavior \/&gt;\r\n            &lt;\/behavior&gt;\r\n            &lt;\/endpointBehaviors&gt;\r\n\r\n<\/pre>\n<\/blockquote>\n<p>Configure endpoint<\/p>\n<blockquote>\n<pre class=\"code\"> &lt;endpoint address=\"api\" binding=\"webHttpBinding\" behaviorConfiguration=\"jsonBehavior\" contract=\"Service.IServiceContract\" \/&gt;\r\n<\/pre>\n<\/blockquote>\n<h2><strong>APIs that support CORS<\/strong><\/h2>\n<ul>\n<li><a href=\"https:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/userguide\/cors.html\">Amazon S3<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/dbpedia-spotlight\/dbpedia-spotlight\/\">DBpedia Spotlight<\/a><\/li>\n<li><a href=\"https:\/\/dropbox.tech\/application\/some-love-for-javascript-applications-2\">Dropbox API<\/a><\/li>\n<li><a href=\"https:\/\/developers.facebook.com\/\">Facebook Graph API<\/a><\/li>\n<li><a href=\"https:\/\/www.flickr.com\/services\/api\/\">Flickr API<\/a><\/li>\n<li><a href=\"https:\/\/foursquare.com\/developer\/\">FourSquare API<\/a><\/li>\n<li><a href=\"https:\/\/developers.google.com\/\">Google APIs<\/a><\/li>\n<li><a href=\"https:\/\/developers.googleblog.com\/en\/google-cloud-storage-adds-several-highly-requested-features\/\">Google Cloud Storage<\/a><\/li>\n<li><a href=\"https:\/\/docs.github.com\/en\/rest#cross-origin-resource-sharing\">GitHub v3 API<\/a><\/li>\n<li><a href=\"https:\/\/www.mediawiki.org\/wiki\/Manual:CORS\">MediaWiki API<\/a><\/li>\n<li><a href=\"http:\/\/prefix.cc\/\">prefix.cc<\/a><\/li>\n<li>PublishMyData<\/li>\n<li><a href=\"https:\/\/developers.soundcloud.com\/docs#crossdomain\">SoundCloud API<\/a><\/li>\n<li><a href=\"https:\/\/developer.spotify.com\/documentation\/web-api\">Spotify Lookup API<\/a><\/li>\n<li><a href=\"http:\/\/sunlightlabs.github.io\/congress\/\">Sunlight Congress API<\/a><\/li>\n<li><a href=\"http:\/\/linkeddata.uriburner.com\/\">URIBurner<\/a><\/li>\n<li><a href=\"https:\/\/developers.google.com\/youtube\/\">YouTube API<\/a><\/li>\n<li>doctape<a href=\"http:\/\/www.programmableweb.com\/api\/doctape\"> API<\/a><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h2 id=\"libraries\">Libraries for implementing CORS<\/h2>\n<ul>\n<li><a href=\"https:\/\/software.dzhuvinov.com\/cors-filter.html\">CORS Filter<\/a>, for Java Web applications<\/li>\n<li><a href=\"https:\/\/github.com\/monsur\/cors-python\">cors-python<\/a>, for Python web apps<\/li>\n<li><a href=\"https:\/\/github.com\/BauweBijl\/gaecors\">Enable CORS on static content in Google AppEngine.<\/a><\/li>\n<li><a href=\"https:\/\/metacpan.org\/release\/RDF-LinkedData\">RDF::LinkedData<\/a> version 0.16 and later<\/li>\n<li><a href=\"https:\/\/github.com\/ebay\/cors-filter\">cors-filter<\/a>: A Java Servlet Filter implementation of server-side CORS for web containers, by eBay Software Foundation<\/li>\n<li><a href=\"https:\/\/github.com\/pouchdb\/add-cors-to-couchdb\">add-cors-to-couchdb<\/a>: CLI to add CORS support to CouchDB, for use in client libraries like PouchDB.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>Thanks for reading this\u00a0<strong>\u00a0<\/strong>post. Hoping this tutorial will help you to <strong>Enable Cross-Origin Resource Sharing<\/strong>.<\/p>\n<p>Please give your comments and remark below.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is Cross-Origin Resource Sharing (CORS) &#8211; Cross-origin resource sharing is fundamental that can make visible the resources\u00a0which are hidden. Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain boundaries. CORS allows web scripts to interact more openly with content outside of the original domain, leading to better integration between<\/p>\n","protected":false},"author":2,"featured_media":3937,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[53],"tags":[],"class_list":["post-3908","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Enable Cross-Origin Resource Sharing - Weblizar Blog<\/title>\n<meta name=\"description\" content=\"Cross-origin resource sharing is fundamental that can make visible the resources which are hidden. Enable Cross-Origin Resource Sharing\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Enable Cross-Origin Resource Sharing - Weblizar Blog\" \/>\n<meta property=\"og:description\" content=\"Cross-origin resource sharing is fundamental that can make visible the resources which are hidden. Enable Cross-Origin Resource Sharing\" \/>\n<meta property=\"og:url\" content=\"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/\" \/>\n<meta property=\"og:site_name\" content=\"Weblizar Blog\" \/>\n<meta property=\"article:publisher\" content=\"http:\/\/www.facebook.com\/weblizarwp\" \/>\n<meta property=\"article:published_time\" content=\"2016-11-07T06:33:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-08-07T10:11:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/i0.wp.com\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png?fit=1920%2C1324&ssl=1\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1324\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Surabhi Shringi\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@weblizar\" \/>\n<meta name=\"twitter:site\" content=\"@weblizar\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Surabhi Shringi\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Enable Cross-Origin Resource Sharing - Weblizar Blog","description":"Cross-origin resource sharing is fundamental that can make visible the resources which are hidden. Enable Cross-Origin Resource Sharing","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/","og_locale":"en_US","og_type":"article","og_title":"Enable Cross-Origin Resource Sharing - Weblizar Blog","og_description":"Cross-origin resource sharing is fundamental that can make visible the resources which are hidden. Enable Cross-Origin Resource Sharing","og_url":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/","og_site_name":"Weblizar Blog","article_publisher":"http:\/\/www.facebook.com\/weblizarwp","article_published_time":"2016-11-07T06:33:54+00:00","article_modified_time":"2025-08-07T10:11:06+00:00","og_image":[{"width":1920,"height":1324,"url":"https:\/\/i0.wp.com\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png?fit=1920%2C1324&ssl=1","type":"image\/png"}],"author":"Surabhi Shringi","twitter_card":"summary_large_image","twitter_creator":"@weblizar","twitter_site":"@weblizar","twitter_misc":{"Written by":"Surabhi Shringi","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#article","isPartOf":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/"},"author":{"name":"Surabhi Shringi","@id":"https:\/\/weblizar.com\/blog\/#\/schema\/person\/e4f45800c865f300baed78fc7436ff65"},"headline":"Enable Cross-Origin Resource Sharing","datePublished":"2016-11-07T06:33:54+00:00","dateModified":"2025-08-07T10:11:06+00:00","mainEntityOfPage":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/"},"wordCount":1539,"commentCount":0,"image":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#primaryimage"},"thumbnailUrl":"https:\/\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png","articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/","url":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/","name":"Enable Cross-Origin Resource Sharing - Weblizar Blog","isPartOf":{"@id":"https:\/\/weblizar.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#primaryimage"},"image":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#primaryimage"},"thumbnailUrl":"https:\/\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png","datePublished":"2016-11-07T06:33:54+00:00","dateModified":"2025-08-07T10:11:06+00:00","author":{"@id":"https:\/\/weblizar.com\/blog\/#\/schema\/person\/e4f45800c865f300baed78fc7436ff65"},"description":"Cross-origin resource sharing is fundamental that can make visible the resources which are hidden. Enable Cross-Origin Resource Sharing","breadcrumb":{"@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#primaryimage","url":"https:\/\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png","contentUrl":"https:\/\/weblizar.com\/blog\/wp-content\/uploads\/2016\/11\/Banner-3-.png","width":1920,"height":1324},{"@type":"BreadcrumbList","@id":"https:\/\/weblizar.com\/blog\/enable-cross-origin-resource-sharing\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/weblizar.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Enable Cross-Origin Resource Sharing"}]},{"@type":"WebSite","@id":"https:\/\/weblizar.com\/blog\/#website","url":"https:\/\/weblizar.com\/blog\/","name":"Weblizar Blog","description":"Update yourself with all the latest tech news revolving around wordpress all at one place","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/weblizar.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/weblizar.com\/blog\/#\/schema\/person\/e4f45800c865f300baed78fc7436ff65","name":"Surabhi Shringi","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/29fe73e02d11025a835bd895f236f92e49f10221f7e8bb38da3784a69d4f4542?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/29fe73e02d11025a835bd895f236f92e49f10221f7e8bb38da3784a69d4f4542?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/29fe73e02d11025a835bd895f236f92e49f10221f7e8bb38da3784a69d4f4542?s=96&d=mm&r=g","caption":"Surabhi Shringi"}}]}},"_links":{"self":[{"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/posts\/3908","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/comments?post=3908"}],"version-history":[{"count":0,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/posts\/3908\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/media\/3937"}],"wp:attachment":[{"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/media?parent=3908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/categories?post=3908"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/weblizar.com\/blog\/wp-json\/wp\/v2\/tags?post=3908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}