【问题标题】:Response to preflight request doesn't pass access control check No 'Access-Control-Allow-Origin' header is present on the requested resource对预检请求的响应未通过访问控制检查 请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-06-20 18:44:30
【问题描述】:

我在 IIS 上托管了 .NET Core WebAPI,我在 startup.cs 中启用了 CORS。

从我的 Angular 应用程序向 API 发出请求时,请求失败,我收到此错误

“从源 'https://test-apps2.contractorconnection.com' 访问 XMLHttpRequest 在 'https://test-api.contractorconnection.com/ERCore_Service/api/LandingPage/Authenticate/Austin.Born/ERCore' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有 'Access-Control-Allow-Origin' 标头存在于请求的资源上。”。

当直接从浏览器或邮递员发出请求时,请求完成并且我得到了我的数据。

我尝试了很多答案,修改了 web.config,并在 Startup.cs

中指定了允许的来源

我在这里遗漏了什么或做错了什么?

Startup.cs 下面

public void ConfigureServices(IServiceCollection services) {
    //  //For JWT Auth
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });
    services.AddScoped<ILandingPage, DAL_LandingPage>();
    services.AddScoped<IDetails, DAL_EstimateDetailPage>();
    services.AddScoped<IQueueDetailsPage, DAL_QueueDetails>();
    services.AddScoped<IAdminDetailPage, DAL_AdminDetailPage>();
    services.AddScoped<IAdminCatSelTab, DAL_AdminCatSel>();
    services.AddScoped<IApplicationSecurityTab, DAL_ApplicationSecurityTab>();

    //services.AddCors();
    services.AddCors(o => o.AddPolicy("MyPolicy", builder => {
        builder.AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins("https://test-apps2.contractorconnection.com", "https://test-apps2.contractorconnection.com/ERCore", "http://localhost:54807/")
            .AllowCredentials();
    }));

    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });
    services.AddDbContext<PrismDataContext1>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));



}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    }
    //app.UseCors(builder => builder.WithOrigins("http://localhost:4200", "https://cc-er-dev-api.primussoft.com", "https://test-apps2.contractorconnection.com", "https://apps2.contractorconnection.com").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
    app.UseCors("MyPolicy");
    app.UseOptions();
    //For JWT Auth
    app.UseAuthentication();
    app.UseMvc();
}

控制器端点

[HttpGet]
[Route("api/LandingPage/Authenticate/{webLogin}/{appName}")]
[HttpOptions]
public JsonResult AuthenticateUser(string webLogin, string appName) {
    string connectionString = _config.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
    Auth auth = new Auth(connectionString);
    User obj = new User();
    try {
        bool hasAccess = auth.Load(webLogin, appName);
        obj.Name = auth.Name;
        obj.ResourceTypeName = auth.ResourceTypeName;
        obj.ClassificationName = auth.ClassificationName;
        obj.Login = auth.Login;
        obj.ResourceID = auth.ResourceID;
        obj.DetailID = auth.DetailID;
        obj.ApplicationID = auth.ApplicationID;
        obj.ResourceTypeID = auth.ResourceTypeID;
        obj.ClassificationID = auth.ClassificationID;
        obj.SecurityFeatures = auth.FeatureAccess;
        obj.CurrentLanguageDescription = auth.CurrentLanguageDescription;
        obj.CurrentLanguageID = auth.CurrentLanguageID;
        var tokenString = BuildToken(obj);
        obj.Token = tokenString;

        Response.Headers.Add("Access-Control-Allow-Origin", "https://test-apps2.contractorconnection.com");

        return Json(obj);
    } catch (Exception ex) {
        string ac = ex.Message;
        return Json(obj);
    }
}

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <cors enabled="true" failUnlistedOrigins="false">
        <add origin="*" allowed="true" />
    </cors>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\ERCore_Service.exe" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

【问题讨论】:

  • IIS 有一个 CORS 模块。
  • @LexLi 我安装了模块,没有成功
  • 模块不会自动工作,除非你给出有效的配置,docs.microsoft.com/en-us/iis/extensions/cors-module/…
  • @LexLi 仍然不起作用,我将我的 Web.config 添加到帖子中进行验证。
  • 此问题可能与我们服务器上的另一层安全性有关。我有另一个开发人员正在检查某事/说他知道出了什么问题。如果问题不在于代码或 IIS,我今天或明天会有答案。

标签: iis asp.net-core .net-core


【解决方案1】:

此问题与名为 Netscaler 的第三方软件有关。这阻止了 Angular 发送的 OPTIONS 预检请求。

NetScaler 为服务器配置 COR,因此您无需在 .NET Core api 中配置 COR。

如果在 .NET Core API 中启用了 CORs,您将收到 Allow-Access-Control-Headers 中命名的多个 url 的 CORs 错误。

我从我的 API 中删除了 CORs 配置,我的合作伙伴 DEV 通过 Netscaler 配置了 CORs。

这完全解决了问题。

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 2018-05-06
    • 2017-11-11
    • 2017-04-09
    • 2017-09-08
    • 2017-10-10
    • 2016-12-24
    • 2020-12-07
    相关资源
    最近更新 更多