Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Microsoft.Owin.Cors middleware do when used with ASP.NET Web Api 2.0?

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:

like image 433
Milen Kovachev Avatar asked Nov 12 '14 13:11

Milen Kovachev


People also ask

What is Microsoft OWIN used for in Web API?

OWIN allows web apps to be decoupled from web servers. It defines a standard way for middleware to be used in a pipeline to handle requests and associated responses. ASP.NET Core applications and middleware can interoperate with OWIN-based applications, servers, and middleware.

What is use of CORS in asp net web API?

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP.


1 Answers

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.

like image 94
Taiseer Joudeh Avatar answered Jan 03 '23 23:01

Taiseer Joudeh