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

我有使用owin中间件保护我的Web API有困难.

我已经安装下面的包装

Install-Package Microsoft.Owin.Cors -Version 2.1.0

以下是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);
  }

我已经在一个链接上举办了这个WebApi项目,比如http://webaip.azurewebsites.net

我试图从另一个网站访问上述API的控制器方法,比如http://mysite.azurewebsites.net
使用上面的代码,我可以调用所有不安全的API方法. (不使用Authorize属性装饰)通过javascript我无法调用/令牌进行身份验证.以下是我的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;
        }

我下错了

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.

注意:我也尝试使用下面的代码.这也不是为我工作.

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

解决方法

您收到该错误的原因是因为您已经为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;
    }

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....