GET and POST requests from blocked origin still executed
I'm trying to implement CORS policies in my ASP .NET Core 2 project (Microsoft.AspNetCore.All 2.0.3 and Microsoft.AspNetCore.Cors 2.0.1). I'm getting some very strange behavior that I can't quite understand the cause of. I created a simple ExpressJs server to simulate a client making cross-origin requests so I can be sure that my API is properly denying access. Instead, I was seeing GET and POST requests from a non-authorized origin make it through my CORS policy and return data to the client where the browser (Chrome) would throw a console error about violating CORS. I've included the relevant parts of my Startup.cs file, a snippet of one of my controllers, and an example of how my client is making the request.
Startup.cs
public void ConfigureServices(IServiceCollection services) {
// CORS - Policies
services.AddCors(options => {
options.AddPolicy("AllowReadFromOrigin", builder => {
builder.AllowAnyMethod()
.WithOrigins("http://lab.local.com:4000")
.WithHeaders("accept", "content-type", "origin", "x-test");
});
});
...
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
// CORS - Global Policy
app.UseCors("AllowReadFromOrigin");
...
app.UseMvc();
}
Controller
public class BaseController : Controller
{
protected BasicUser currentUser { get { return new BasicUser(); } }
protected Stopwatch timeTaken { set; get; } = Stopwatch.StartNew();
public BaseController() { }
public JsonResult sendOKResponse<T>(T payload) {
var contents = new BasicResponse<T>(payload, timeTaken);
return Json(contents);
}
}
[Produces("application/json")]
[Route("list")]
public class ListController : BaseController {
private readonly ILogger _logger;
public ListController(ILogger<ListController> logger) {
_logger = logger;
}
[HttpGet]
[ProducesResponseType(typeof(BasicResponse<IEnumerable<string>>), 200)]
public JsonResult Get() {
var result = Relational.getDataForUser(currentUser.Email);
return sendOKResponse(result);
}
}
Client
$("#btnGet").on("click", function (e) {
$.ajax({
type: "GET",
url: "http://local.api.com/cpn/list"
}).done(function (data) {
console.log(data);
}).fail(function (message) {
console.log("GET Request Failed");
});
});
In the interest of figuring out what the underlying problem is, I increased the system logging level to DEBUG to try and capture as much information as possible. Luckily, I think I did manage to find enough information to identify that there is an issue or, at the very least, some key information missing from the documentation.
[11:25:04 INF] Request starting HTTP/1.1 GET http://local.api.com/cpn/list
[11:25:04 DBG] The request has an origin header: 'http://lab.local.com:4500'.
[11:25:04 INF] Policy execution failed.
[11:25:04 INF] Request origin http://lab.local.com:4500 does not have permission to access the resource.
[11:25:04 DBG] The request path does not match the path filter
[11:25:04 DBG] Request successfully matched the route with name 'null' and template 'list'.
[11:25:05 DBG] Executing action CpnApi.Controllers.ListController.Get (CpnApi)
[11:25:05 INF] Executing action method CpnApi.Controllers.ListController.Get (CpnApi) with arguments (null) - ModelState is Valid
[11:25:05 DBG] Executed action method CpnApi.Controllers.ListController.Get (CpnApi), returned result Microsoft.AspNetCore.Mvc.JsonResult.
[11:25:05 INF] Executing JsonResult, writing value CpnApi.Models.BasicResponse`1[System.Collections.Generic.IEnumerable`1[CpnApi.Models.ListMetadata]].
[11:25:05 INF] Executed action CpnApi.Controllers.ListController.Get (CpnApi) in 512.5151ms
[11:25:05 INF] Request finished in 1199.5144ms 200 application/json; charset=utf-8
This is produced from making a simple GET request to the API from an unathorized origin (port 4500 instead of 4000). It's apparent that the framework correctly identified that the domain is not allowed to make this request, but then it still allowed it to continue.
My client is a simple ExpressJs server serving up a page that implements jQuery to make an GET request via AJAX to the API method. If I do something that triggers an OPTIONS check (ie. adding a custom header), then this request is correctly evaluated and blocked but, in it's simplest form (example above), it's still allowed through.
Please let me know if there is any more information I can provide.
I'm not sure if you've enabled cors+mvc correctly. Check the docs. https://docs.microsoft.com/en-us/aspnet/core/security/cors
I used that documentation to do my initial implementation. After a second look I thought it might've been that I missed this part:
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowReadFromOrigin"));
});
... but adding that and removing the call to app.UseCors() didn't change anything.
If you can think of anything specific in that document for me to try, I'll give it a shot.
Looks good. Docs could be a little outdated.
services.AddCors(options =>
{
options.AddPolicy("fiver",
policy => policy.WithOrigins("http://localhost:21314"));
});
services.AddMvc(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("fiver"));
});
@javiercn / @jbagga can you take a look?
This is not a bug. It's how CORS works. The request still executes on the server, but the browser denies the page access to the results.
For GET requests CORS allows the browser to directly send the request with an Origin header as GET requests are considered safe (no side-effects). For other verbs like POST browsers send a preflight request using the OPTIONS method and Allow-access-control-* headers to identity the specific method they want to use. If the preflight request passes, then the browser sends the actual request (For example a POST request).
The key here is that the page never gets the results of any request as the response doesn't contain any allow-origin response header and based on that, the browser blocks access to the data.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for details