CORS on OWIN and accessing /token causes 'Acce

2019-01-16 19:51发布

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("*","*","*"));
}

7条回答
闹够了就滚
2楼-- · 2019-01-16 20:53

You should not have same header twice (I think it is a dictionary data structure)

In my case I had this line in a provider class which was not needed because I'm already enabling cores in startup.cs

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

in startup.cs I had and I kept:

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
查看更多
登录 后发表回答