DesertFoxAZ
DesertFoxAZ

Reputation: 489

Access-Control-Allow-Origin requests with web api

We have an intranet application we are working on with an AngularJS front end and a Web Api back end. It's basically a redesign of an existing ASP.NET/WCF app and it's only used by a few of our employees.

We had intended to enforce some security in this version (the old one had none) using Windows Authentication and we've had some problems getting that to work with browsers other than Internet Explorer. Chrome, for example always comes back with a 401-Unauthorized error.

I've been instructed to skip the security features for now (yeah I know, not a good idea) so I've disabled them but now I'm seeing an error when I attempt to talk to the API (in a separate project), but in Chrome and not in IE.

XMLHttpRequest cannot load http://localhost:62415/api/Emails. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50900' is therefore not allowed access. The response had HTTP status code 401.

We've enabled CORS in our API project so I am not sure what I need to do here. We are using localhost in our local development but in QA and production these sites will be using URLs with different subdomains within the same domain.

I am using a Startup class in my project and it has this method:

public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        WebApiConfig.Register(config);
        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config);
    }

I must be missing something. We originally had this code in our WebApiConfig but restoring it didn't fix anything:

var cors = new EnableCorsAttribute("*", "*", "*");

cors.SupportsCredentials = true;
config.EnableCors(cors);

Any help is appreciated.

Upvotes: 1

Views: 676

Answers (1)

Thảo Frederic
Thảo Frederic

Reputation: 61

Don't need to add:

var cors = new EnableCorsAttribute("", "", "*"); config.EnableCors(cors);

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. However, You can pass that by:

  • install Microsoft.Owin.Cors package in nuget
  • add this method in Startup.cs
    public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
        }

Upvotes: 1

Related Questions