6

I have an ASP.NET Web Api 2.0 project with token authentication and everything done mainly following this article:

Token Based Authentication using ASP.NET Web API 2, Owin, and Identity, Bit Of Technology

But I am struggling to understand what exactly this line of code in my Startup.cs does:

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

This does not make the Web Api add the Access-Control-Allow-Origin header to my API responses, in other words it does not enable Cors in my Web Api (still trying to understand how to do this by the way). It does not even add it to my bearer token authentication server response. I have to have this code to my OAuthAuthorizationServerProvider:

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 

to enable Cors on my token provider end point responses.

So what is the use of this Microsoft.Owin.Cors middleware anyway? Because everywhere I read about Web Api 2.0 and Cors this line of code

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

comes up:

Johan Aspeling
  • 765
  • 1
  • 13
  • 38
Milen Kovachev
  • 5,111
  • 6
  • 41
  • 58

1 Answers1

6

thanks for following my tutorial.

This LOC app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); is used to enable CORS for the API itself (Any controller inheriting from ApiController).

But for the Authz server and end point /token this make no affect that is why I've to add context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); This end point is not part from the API and doesn't inherit from ApiController class.

Hope this answers your question.

Taiseer Joudeh
  • 8,953
  • 1
  • 41
  • 45
  • 1
    Hi Taiseer, thanks for answering! But CORS is ont enabled in my ApiControllers. I have to add this line to my Startup.cs and then it works: configuration.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST")); You can see others having a similar problem here: http://stackoverflow.com/questions/20079813/how-to-make-cors-authentication-in-webapi-2 – Milen Kovachev Nov 13 '14 at 11:23
  • That is strange, if you followed my article without missing anything you will notice that I'm enabling CORS using this LOC only. – Taiseer Joudeh Nov 13 '14 at 22:41
  • 2
    You are right app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll) does enable cors on the Web Api. I had a deployment problem with the web api which was breaking the cors. Thanks for your answer and article! – Milen Kovachev Nov 17 '14 at 12:56
  • @TaiseerJoudeh Thanks for a great article and for taking the time to show all the code you added rather than assuming someone understood the middleware. Your article and the explanations went a long way to help me understand OAuth better. – webworm Jun 30 '16 at 11:50