By default, browsers abide by the Same-Origin policy, which is that documents (Or in most cases scripts) cannot interact with a resource from another domain. It isolates, for example, a malicious script being able to do “too much”. A script loaded from a third party should not be able to call your own API. However in some cases this actually may be warranted.
CORS or Cross-Origin Resource Sharing is a way to by-pass this limitation/security measure for legitimate reasons. The most common in the context of ASP.net core is that you are building a Single Page Application, and you wish to host your API on another domain. For example your website is www.mywebsite.com and your API is api.mywebsite.com. Any scripts be they from jQuery, Angular, React, Backbone, whatever cannot make HTTP calls from www.mywebsite.com to api.mywebsite.com.
Configuring CORS In ASP.net Core
Let’s get going and see how this works in ASP.net Core
First you need to add the Microsoft Cors package from Nuget.
You then need to add the CORS services. In your startup.cs in your ConfigureServices method you should have something similar to the following :
public void ConfigureServices(IServiceCollection services)
Next you need to add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
app.UseCors( options => options.WithOrigins("http://www.mydomain.com").AllowAnyMethod() );
The options lambda is a fluent API so you can add/remove any extras you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc) so you can only expose GET calls cross domain etc.
Two very important points.
- Incase it wasn’t obvious, the above is to be done on your API not your web project!
- Your protocol is important. http://www.mydomain.com is not the same as https://www.mydomain.com