Alex Smotritsky
Alex Smotritsky

Reputation: 153

asp.net web api 2 CORS and authentication authorization configuration

I've created an asp.net web api 2 service with individual account security. I'm trying to call it form AngularJs as per this example: http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En could not get that to work so added some config from here: How to make CORS Authentication in WebAPI 2?

and can't get past this error: XMLHttpRequest cannot load 'serverRegisterUrl'. The 'Access-Control-Allow-Origin' header contains multiple values 'clientUrl, *, *', but only one is allowed. Origin 'clientUrl' is therefore not allowed access.

I don't understand this error message. I think that Access-Control-Allow-Origin string means allow origin clientUrl, all headers, all methods

I don't understand the problem. If I'm supposed to just specify the origin alone somewhere, I don't know where that is.

I'm running this on Microsoft Azure and using vs express for web 2013 update 2 just in case it matters.

I unfortunately had to take my links out of the error message because I need atleast reputation 10 here to post more then 2 links in a question.

Upvotes: 5

Views: 6615

Answers (3)

fransHbrink
fransHbrink

Reputation: 374

Just adding to @AlexSmotritsky's answer.

To make use of the UseCors method in

app.UseCors(CorsOptions.AllowAll);

remember to install the Microsoft.Owin.Cors NuGet package and add the

using Microsoft.Owin.Cors; directive.

Upvotes: 5

Alex Smotritsky
Alex Smotritsky

Reputation: 153

I got it working, I think it came down to configuration. Web.config: no "Access-Control-Allow-Origin" customHeaders node

Startup.Auth.cs:
// This must come first to intercept the /Token requests app.UseCors(CorsOptions.AllowAll);

// Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions);

WebApiConfig.cs: (not enabling cors here) //var cors = new EnableCorsAttribute("*", "*", "*"); //config.EnableCors(cors);

AccountController.cs: attribute on GetExternalLogin method: [EnableCors(origins: "*", headers: "*", methods: "*")]


I think that's my whole current CORS config.

Upvotes: 10

Shaun Xu
Shaun Xu

Reputation: 4656

It seems that your Access-Control-Allow-Origin value was clientUrl, *, * which might be invalid. It only allows one value. You can put * means all origins are allowed, or the one you specified, for example your AngularJS host.

I had put my code at https://gist.github.com/shaunxu/8414a78cd8074432fc69 This might not be the east way but it works in my application.

Upvotes: 0

Related Questions