Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

asp.net web api2 - CORS on OWIN and accessing /token causes 'Access-Control-Allow-Origin' error

I am having trouble with securing my Web API using owin middle ware.

I have installed below package

Install-Package Microsoft.Owin.Cors -Version 2.1.0

And below is ConfigureAuth.cs code.

 public void ConfigureAuth(IAppBuilder app)
 {                
      //...
      app.UseOAuthBearerTokens(OAuthOptions);    
      ///Install-Package Microsoft.Owin.Cors -Version 2.1.0
      app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  }

I have hosted this WebApi project on a link , say ,http://webaip.azurewebsites.net

I am trying to access controller methods of above API from another site, say , http://mysite.azurewebsites.net With above code in place I am able to invoke all the methods of API which are not secure. (Not decorated with Authorize attribute) Through javascript I am not able to invoke /Token for authentication. Below is my javascript code.

function LogIn() {
            var loginData = {
                grant_type: 'password',
                username: 'username',
                password: 'password',                
            };

            $.ajax({
                type: 'POST',
                url: 'http://webaip.azurewebsites.net/Token/',
                data: loginData               

            }).done(function (data) {
                alert('logged in');
                alert(data);
            }).fail(function (data) {
                alert('login problem')
            }).error(function (data) {
                alert('error invoking API');
            });
            return false;
        }

I am getting below error

XMLHttpRequest cannot load http://webaip.azurewebsites.net/Token/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 404.

Note: I have also tried to use below code with. It's not working for me either.

public static void Register(HttpConfiguration config)
{
     var json = config.Formatters.JsonFormatter;
     config.Formatters.Remove(config.Formatters.XmlFormatter);
     //Need to have  Microsoft.AspNet.WebApi.Cors package installed.
     config.EnableCors(new EnableCorsAttribute("*","*","*"));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After many hours of searching and looking at many many different solutions to this i have managed to get this working as per the below.

There are a number of reasons this is happening. Most likely you have CORS enabled in the wrong place or it is enabled twice or not at all.

If you are using Web API and Owin Token end point then you need to remove all the references to CORS in your Web API method and add the correct owin method because web api cors will not work with Token endpoint whilst Owin cors will work for both Web API and Token auth end points so lets begin:

  1. Make sure you have the Owin Cors package installed
  2. Remove any line that you have eg.config.EnableCors(); from your WebAPIconfig.cs file
  3. Go to your startup.cs file and make sure you execute Owin Cors before any of the other configuration runs.

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        ConfigureAuth(app);
    
  4. If your still having problems go to: Startup.Auth.cs and ensure you have the following in your ConfigureAuth method (you shouldnt need this if your startup.cs file is correct)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...