OWIN上的CORS和访问/令牌导致'Access-Control-Allow-Origin'错误

use*_*747 21 cors asp.net-web-api2

我使用owin中间件保护我的Web API时遇到问题.

我安装了下面的包

Install-Package Microsoft.Owin.Cors -Version 2.1.0
Run Code Online (Sandbox Code Playgroud)

以下是ConfigureAuth.cs代码.

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

我在一个链接上托管了这个WebApi项目,比如http://webaip.azurewebsites.net

我试图从另一个站点访问上述API的控制器方法,比如说,http: //mysite.azurewebsites.net上面的代码我可以调用所有不安全的API方法.(未使用Authorize属性修饰)通过javascript我无法调用/ Token进行身份验证.以下是我的javascript代码.

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;
        }
Run Code Online (Sandbox Code Playgroud)

我收到了以下错误

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.
Run Code Online (Sandbox Code Playgroud)

注意:我也尝试使用下面的代码.它也不适合我.

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("*","*","*"));
}
Run Code Online (Sandbox Code Playgroud)

Pio*_*ski 41

经过几个小时的搜索并查看了许多不同的解决方案,我已经设法按照下面的方式工作.

这种情况有很多原因.您很可能在错误的位置启用了CORS,或者启用了两次或根本没有启用CORS.

如果您正在使用Web API和Owin Token端点,那么您需要删除Web API方法中对CORS的所有引用并添加正确的owin方法,因为web api cors将无法使用Token端点,而Owin cors将适用于两个Web API和Token auth端点让我们开始:

  1. 确保安装了Owin Cors软件包
  2. 删除你拥有的任何行eg.config.EnableCors(); 从您的WebAPIconfig.cs文件
  3. 转到您的startup.cs文件,确保在任何其他配置运行之前执行Owin Cors.

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        ConfigureAuth(app);
    
    Run Code Online (Sandbox Code Playgroud)
  4. 如果仍有问题请访问:Startup.Auth.cs并确保在ConfigureAuth方法中有以下内容(如果您的startup.cs文件正确,则不需要此项)

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

  • 这是对我的团队有用的唯一答案.所有其他答案打破了应用程序的其余部分.感谢您解释删除其他CORS配置的必要性. (2认同)
  • @SouthShoreAK很高兴我经历了同样的痛苦。我唯一要添加的是人们需要知道添加Owin.Cors软件包。 (2认同)

小智 20

您获得该错误的原因是因为您已为webapi启用了CORS,但未为您的/ Token端点启用此功能,这会在webapi管道获取其CORS设置之前初始化.

所以除了你在WebApiConfig.cs中已经完成的工作之外

您应该执行以下操作:(假设您有一个标准的WebAPI 2项目)

**打开文件:App_Start/IdenityConfig.cs**并添加以下行//允许cors为...

我在正常的项目模板中保持原样不变

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        // Allows cors for the /token endpoint this is different from webapi endpoints. 
        context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });  // <-- This is the line you need

        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<IdentityDb>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = true,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

       // rest ommited ... 
        return manager;
    }
Run Code Online (Sandbox Code Playgroud)

  • 它适用于 /token,但现在开始为 /api 抛出同样的问题...:( 如果我删除您提到的行,/api 开始正常工作... (2认同)

Oma*_*ani 3

查看我对这个问题的回答

另外,如果您使用 angularJS 作为客户端,您可以查看我的文章,其中展示了如何从 AngularJS 客户端使用 Web API 2(个人用户帐户 + CORS 启用)。

希望有帮助。