toadflakz
toadflakz

Reputation: 7934

Disable CORS for single method in ApiController

I have a REST API using OWIN with Web Api 2 Controllers. I need to expose an Authenticate method but only to requests coming from the webserver hosting an AngularJS application (same host as the REST API), which means as far as I'm aware than I need to disable CORS for that one method only.

An example of what my ApiController class looks like would be (RequireHttpsAttribute enforces SSL URL request scheme):

[Authorize]
[RequireHttps]
[RoutePrefix("api/v1")]
public class RestController : ApiController
{
    [AllowAnonymous, Route("Authenticate")]
    public async Task<IHttpActionResult> Authenticate([FromBody] AuthenticationModel authenticationModel)
    { ... }

    [HttpGet, Route("SecureData/{id:int}")]
    public async Task<IHttpActionResult> GetSecureData(int id)
    { ... }

    [HttpPost, Route("SecureData")]
    public async Task<IHttpActionResult> CreateSecureData([FromBody] SecureDataModel data)
    { ... }

    [HttpPut, Route("SecureData")]
    public async Task<IHttpActionResult> UpdateSecureData([FromBody] SecureDataModel data)
    { ... }
}

The OWIN CORS configuration appears to be a blanket application of policy, via the CorsPolicy class and app.UseCors(CorsPolicy.AllowAll) in an OWIN Startup class.

The resources I have found (including other SO questions such as this one) point to the fact that OWIN CORS and ASP.NET CORS are not compatible with each other, so it doesn't appear that I can simply decorate the method with DisableCorsAttribute (I also currently don't have any ASP.NET dependencies in my project so I would be adding all the dependencies for that single attribute!).

My question is: How do I disable CORS in OWIN for a single Web Api 2 Controller method?

Upvotes: 0

Views: 794

Answers (1)

MichaelDotKnox
MichaelDotKnox

Reputation: 1310

The simple answer is that you can't. OWIN middleware is not designed to do that. It is completely agnostic of the application. It's not that the OWIN CORS is not compatible with the ASP.NET CORS, they just live in different scopes within the pipeline and are unaware of each other. So you can't just put an attribute on a method or somehow decorate a method so it is ignored by CORS.

That said, the more complex answer is that you can create your own ICorsPolicyProvider, have it look at the path and decide if CORS should be used or not. You can clone the katana repository from CodePlex here https://katanaproject.codeplex.com and take a look at how the existing CorsPolicyProvider.cs file implements and modify it to your purposes.

Sorry I can't give you any code right now. If I get a few spare minutes later today, I'll see if I can give you an example.

Hope that helps.

Upvotes: 1

Related Questions