Cross-Origin Resource Sharing, commonly referred to as CORS, is a security feature implemented in web browsers to prevent web pages from making requests to a different origin (domain, protocol, or port) than the one the web page was loaded from. This tutorial will cover the basics of CORS, why it’s necessary, and how to configure your server to handle CORS requests.
What is CORS?
CORS is a mechanism that allows a web page to make requests to a different origin (domain, protocol, or port) than the one the web page was loaded from. By default, web browsers enforce the same-origin policy, which prevents a web page from making requests to a different origin. This policy helps prevent malicious scripts from making unauthorized requests on behalf of the user.
Why is CORS necessary?
CORS is necessary because it allows web pages to make requests to APIs or services hosted on different origins. Without CORS, a web page would not be able to make requests to an API hosted on a different domain, which would limit the functionality of many web applications.
How does CORS work?
When a web page makes a request to a different origin, the browser sends an OPTIONS request (also known as a preflight request) to the server before sending the actual request. This preflight request asks the server if it allows requests from the origin that made the request. The server then responds with headers indicating what methods and headers are allowed.
Configuring CORS on your server
To configure CORS on your server, you need to set specific headers in your response. These headers include:
Access-Control-Allow-Origin
: specifies which origins are allowed to make requests to your server.Access-Control-Allow-Methods
: specifies which HTTP methods are allowed (e.g., GET, POST, PUT, DELETE).Access-Control-Allow-Headers
: specifies which headers are allowed in the request.Access-Control-Max-Age
: specifies how long the browser should cache the CORS configuration.
Here’s an example of how to set these headers in a PHP application:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
In an ASP.NET Core Web API, you can configure CORS by adding the Microsoft.AspNetCore.Cors
package and configuring it in your Startup.cs
file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAllHeaders");
}
Handling preflight requests
Preflight requests are sent by the browser before making an actual request to your server. These requests ask your server if it allows requests from the origin that made the request. To handle preflight requests, you need to respond with the correct headers and a 200 OK status code.
Here’s an example of how to handle preflight requests in PHP:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
http_response_code(200);
exit;
}
Conclusion
CORS is an important security feature that prevents web pages from making unauthorized requests to your server. By understanding how CORS works and configuring your server to handle CORS requests, you can ensure that your web application remains secure and functional.
Example use case
Suppose you have a web page hosted on http://example.com
that makes requests to an API hosted on https://api.example.com
. To enable CORS for this scenario, you would set the following headers in your API response:
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token
This would allow the web page hosted on http://example.com
to make requests to your API hosted on https://api.example.com
.