0

So I've developed an asp .net core API that has to allow cross domain access. I've been able to get everything setup and running. I've enabled CORS and want it to apply the same setting across all of my endpoints so have the following in my Config method:

app.UseCors(builder => builder.WithOrigins(
     "http://localhost:3000",
     "http://localhost:3001",
     "https://staging.example.com",
     "https://production.server.com")
     .AllowAnyMethod()
     .AllowAnyHeader()
     .AllowCredentials());

And in my ConfigureServices method:

services.AddCors();

The code is before the MVC middleware and when running locally I have to send requests from localhost:3000 as all others are rejected/blocked (as expected).

Also on staging and live the app works fine and can call the API without any issues.

However, when deployed to the staging or production I can call the API from my local machine using Postman as well as by pointing my local copy of the web app (an AngularJS app) to the API.

Maybe I'm missing something or my understanding is wrong but I thought this shouldn't be allowed! And if not then any thoughts about where I may be going wrong? It seems as though my API is allowing any request from any domain.

Ben Thomson
  • 1,083
  • 13
  • 29
  • See the answer at https://stackoverflow.com/questions/43432743/will-asp-net-core-cors-policy-prevent-resource-access-from-non-browser-requests/43432787#43432787 – sideshowbarker Sep 15 '17 at 07:27

1 Answers1

3

CORS is only about ajax requests from web pages in domain A to domain B. Postman is a dev tool not a web page, and it doesn't care about CORS, that's why your Postman requests are not blocked. It is the same as building console application making http requests to your api, i.e. the requests won't be blocked. Regarding the angular client, your requests are not blocked because you allow http://localhost:3000 and http://localhost:3001 origins. If you try ajax calls from lets say http://localhost:3002, it should be blocked

An option here is to extract the origins in config/json files. For example, you will have appsettings.Development.json with something like:

{
  "cors": {
    "Origins": ["http://localhost:3000", "http://localhost:3001"]
  }
}

And additional files appsettings.Production(Staging).json when running in Production(Staging) environment.

If you want to totally secure your rest API, you should consider adding JWT authentication. For example, adding Identity Server 4 in the game, or using Azure B2C AD. But this mean that you should also add Login for the Angular client.

regnauld
  • 4,046
  • 3
  • 23
  • 22
  • Thanks that sorted me out. I'm also going to look in to having an API key for the client. We can't have users login as it is an anonymous questionnaire/survey application. – Ben Thomson Sep 20 '17 at 03:43