加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:57:45 所属栏目:asp.Net 来源:网络整理
导读:我有使用owin中间件保护我的Web API有困难. 我已经安装下面的包装 Install-Package Microsoft.Owin.Cors -Version 2.1.0 以下是ConfigureAuth.cs代码. public void ConfigureAuth(IAppBuilder app) { //... app.USEOAuthBearerTokens(OAuthOptions); ///Inst
我有使用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;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读