微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
    }

原文地址:https://www.jb51.cc/aspnet/249798.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐