Cross-origin resource sharing (CORS)
Browser security prevents a webpage from making AJAX requests to another domain. This restriction is called the same-origin policy. However, there are some situations where you want to let other sites call your web API.
Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. When you use CORS, a server can explicitly allow some cross-origin requests while rejecting others.
For more information, see Enabling Cross-Origin Requests in ASP.NET Web API.
This topic describes:
-
Configuring CORS
-
Handling a preflight request
Configuring CORS
Sitecore provides CORS support for Web API services. It applies to all custom Web API services as well as the ones provided by Sitecore (for example the Item Service and the OData Item Service).
You can configure CORS in three ways:
-
Globally for all Web API services (configured in the
Sitecore.Services.Client.config
file). -
Using an API key.
-
Using the
EnableCors
attribute.
Global configuration
The Sitecore.Services.Client.config
file has a section called allowedOrigins
. You register origins in this section. You do not have to provide an API key in requests to enable CORS, but origins that are registered via an API key or the EnableCors
attribute take precedence over the ones that registered globally.
You add allowed origins similar to this:
<allowedOrigins hint="list:AddOrigin">
<origin>http://example.com</origin>
<origin>http://localhost:39467</origin>
</allowedOrigins>
Using an API key
If you configure a service to use an API key, Sitecore resolves the allowed origins from this key, provided in the request.
You specify the allowed origins in the CORS Origins
field of an API key item.
The OData Item Service
is configured to use API keys and can get allowed origins from them.
Using the EnableCors attribute
You can enable CORS by adding the EnableCors attribute (from the System.Web.Http.Cors
namespace) to a controller class and specifying the origins
, headers
, and methods
parameters as needed.
For example, this controller has wildcard values for all of the resource restriction parameters:
[ServicesController][EnableCors(origins: "*", headers: "*", methods: "*")]public class TestController : ServicesApiController { ... }
In production environments, you must use a more restrictive definition of what can access resources.
Handling a preflight request
Under certain circumstances (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS for details), browsers generate a preflight request to make sure that the requested origin is allowed.
Browsers do not pass custom headers together with preflight requests. Therefore, an API key ID specified in headers does not reach the server.
In order to configure allowed origins via an API key, you have to pass the API key ID as a URL parameter (http://{host}/sitecore/api/ssc/aggregate/content/Items?sc_apikey={api key})
.