What Is CORS?
Before we going into the basic question "What is CORS?", let us imagine a scenario related to that.
Let us start with a very basic example.
Suppose there are two URLs like the ones below:
http://example.com/abc.html
http://example.com/xyz.html
The above URLs look almost identical, so let us call them, "same origin."
Now, after making a little twist, we have some more URLs, as shown below:
http://example.in //// You have a different domain.
http://www.example.com/xyz.html //// You have a different sub domain
http://example.com:7000/abc.html //// Oh man, you have different ports!
So, since the URLs in the above example do not look similar, we'll use the term "Different origin" to describe them.
If the CORS is not enabled you might get an exception like the one below while trying to access another domain using an ajax call:
XMLHttpRequest
cannot load http://www.example.com/. No 'Access-Control-Allow-Origin'
header is present on the requested resource.Why?
Because browser security prevents a web page from making ajax requests to another domain. This restriction is called the same-origin policy and prevents a malicious site from reading sensitive data from another site.
But what if we want to allow other domains to access our APIs?
Now the question is, "What is CORS?"
CORS stands for Cross-Origin Resource Sharing.
Per the ASP.NET Core docs, "CORS is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others."
Simply put - CORS gives you the power to allow cross-domain calls from the specified domains.
How Does CORS Work?
- Once we use CORS, new
HTTP
headers are introduced which enable cross-origin requests. - "If the browser supports CORS, the browser sets those headers automatically for cross-origin requests."
- These cross-origin requests are then sent to the server that contains the origin header which includes the domain information.
- If everything goes well with the server, the server adds an Access-Control-Allow-Origin header in the response.
- The value of the header,
Access-Control-Allow-Origin
, could be * in case any origin should be allowed or for when we want to allow any specific domain in the name of the domain, i.e.Access-Control-Allow-Origin: http://example.com
- If the response does not include the header Access-Control-Allow-Origin, the request fails.
Example
Access to XMLHttpRequest at 'http://localhost:54461/api/user/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error: HttpResponseError
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
status: 0
statusText: "Unknown Error"
url: "http://localhost:54461/api/user/"
ok: false
name: "HttpErrorResponse"
message: "Http failure response for http://localhost:54461/api/user/: 0 Unknown Error"
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
__proto__: HttpResponseBase
Install CORS Nuget Package
To install Microsoft ASP.NET Core Cross-Origin Support, run the following command in the Package Manager Console or you can download from nuget package:
Install-Package Microsoft.AspNetCore.Cors
In the ConfigureServices method of your startup.cs, add the CORS services.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
Then in your Configure method of your startup.cs, add the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://localhost:4200").AllowAnyMethod()
);
app.UseMvc();
}
I hope this blog will helpful for you. If you need more information please do comment on comment box.
Happy Coding ;)