Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS is not working in web api with OWIN authentication

Tags:

In my application i am using web api with token based authentication with CORS support, but when client request for the token, an error occured due to CORS (Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (my site name) . This can be fixed by moving the resource to the same domain or enabling CORS.)

I had configured everything required for CORS support ( i think so). here my configuration

Owin start up class

   public class Startup     {         public void Configuration(IAppBuilder app)         {               var config = new HttpConfiguration             {                 DependencyResolver = new StructureMapWebApiDependencyResolver(container)              };               WebApiConfig.Register(config);  // registering web api configuration             app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  // cors for owin token pipeline             app.UseWebApi(config);             ConfigureOAuth(app);           }          public void ConfigureOAuth(IAppBuilder app)         {             var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()             {                  AllowInsecureHttp = true,                 TokenEndpointPath = new PathString("/token"),                 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),                 Provider = new SimpleAuthorizationServerProvider()             };             // Token Generation             app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);             app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());          }     } 

And my webapi configuration

public static class WebApiConfig     {         public static void Register(HttpConfiguration config)         {             config.EnableCors();  // Corse support for Web api             config.MapHttpAttributeRoutes(); // attribute based urls              config.Routes.MapHttpRoute(                 name: "DefaultApi",                 routeTemplate: "api/{controller}/{id}",                 defaults: new { id = RouteParameter.Optional }             );          }     } 

here configuration in web.config

<system.webserver>  <httpProtocol>       <customHeaders>         <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request-->         <add name="Access-Control-Allow-Origin" value="*" />         <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />       </customHeaders>     </httpProtocol> </system.webserver> 

and my request header from mozilla

Accept  application/json, text/plain, */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Content-Length  67 Content-Type    application/x-www-form-urlencoded; charset=UTF-8 Host    talenterp Origin  http://192.168.1.11:85 Referer http://192.168.1.11:85/ User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0 

The URLs of Apps are

Server app (which should support CORS)

{http://talenterp} 

Token end point :

{http://talenterp/token} 

Client app

{http://talentmvc:85} 

NB: I already added

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

in GrantResourceOwnerCredentials() method of my AuthorizationServerProvider

like image 395
Binson Eldhose Avatar asked Jul 28 '14 06:07

Binson Eldhose


People also ask

How do I fix the CORS issue in Web API?

First, we need to enable CORS in WebAPI, then we call the service from other application AJAX request. In order to enable CORS, we need to install the JSONP package from NuGet (see Figure3). After adding Jsonp package, we need to add the following code-snippet in App_Start\WebApiConfig. cs file.

What is CORS in asp net core?

CORS means cross-origin resource sharing. You'll see more in just a minute, but in a nutshell, CORS is a mechanism—an HTTP protocol, to be exact—that allows web applications to access resources hosted on different domains (or origins.)

How to enable Cors request in ASP NET Web API?

Please Sign up or sign in to vote. For enabling the CORS request in the ASP.NET Web API project, we have to download the cors package from the Nuget, i.e., Microsoft.AspNet.WebApi.Cors. Open up the Nuget Package Manager console from the Visual Studio Tools Option —> Library Package Manager —> Package Manager Console.

How do I enable Cors for a webservice controller?

The above CORS package installs, along with any dependencies, into the ASP.NET Web API WebService project. Now open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.Register method. Next, add the [EnableCors] attribute to the Controller class, as follows:

What is Cors in ASP NET Core?

Enable Cross-Origin Requests (CORS) in ASP.NET Core Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

How do I enable Cors in Visual Studio Code?

Enable CORS. Now let's enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command: Install-Package Microsoft.AspNet.WebApi.Cors


2 Answers

Be sure you've got only

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

configured, and not also the old style 'config.EnableCors()' in your Global.asax or WebApiConfig. Furthermore: place the above statement as the first one in your owin Startup class. Yes that really makes a difference, setting it later can also cause cors to not work.

public partial class Startup {     public void Configuration(IAppBuilder app)     {         app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);          ... etc 
like image 139
Elger Mensonides Avatar answered Oct 22 '22 14:10

Elger Mensonides


OWIN and Microsoft.AspNet.WebApi.Cors are two separate libraries and each one needs separate configuration.

Disable use of CORS with OWIN:

public void Configuration(IAppBuilder app) {         //app.UseCors(CorsOptions.AllowAll); 

Find GrantResourceOwnerCredentials method and add Access-Control-Allow-Origin to context so when it returns a call after authentication is completed that browser finds the header and accepts it.

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

Now install Microsoft.AspNet.WebApi.Cors package from Nuget to your webapi project, and add this to Register method

public static void Register(HttpConfiguration config) {         var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");          config.EnableCors(cors); 

This did it for me.

like image 23
Dado Kljuco Avatar answered Oct 22 '22 15:10

Dado Kljuco