浏览器未发送启用了CORS的跨域跨域Cookie

reg*_*ahn 5 .net javascript c# cors asp.net-core

我有一个.net核心webapi项目设置为接受跨源请求,如下所示

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(opts => opts
        .WithOrigins("https://fiddle.jshell.net")
        .AllowCredentials()
        .AllowAnyMethod()
        .AllowAnyHeader());

    app.UseHttpsRedirection();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

它具有一个带有GET方法的值控制器,如下所示

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return Ok("cookies: " + string.Join(", ", HttpContext.Request.Cookies.Select(x => x.Key)));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我试图像这样从浏览器发送获取请求

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(opts => opts
        .WithOrigins("https://fiddle.jshell.net")
        .AllowCredentials()
        .AllowAnyMethod()
        .AllowAnyHeader());

    app.UseHttpsRedirection();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

但这不会将cookie从页面发送到api。我在这里想念什么?我已经尝试过所有可以找到的解决方案,包括关闭第三方Cookie

更新资料

因此,我仍然没有答案,为什么这不起作用,或者任何权威人士说您无法跨域发送Cookie(甚至说跨域!=跨域的Cookie)。

我们发现,即使来自的Cookie sub-a.domian.com也不会发送到sub-b.domain.com。我们“解决”的方式,这是要创建一个永久绑定到一个cookie domain.com,因为这些cookie 发送到sub-a.domain.comsub-b.domain.com

Twi*_*her 0

CORS 唯一做的就是让浏览器使用跨域请求的响应,它不会使 cookie 跨域(有关将 cookie 附加到请求的条件的更多详细信息,请参阅规范,没有提及 CORS根本没有)。

如果 cookie 可以随着跨源请求发送,那将是一个主要的安全缺陷,因为它将允许外部域从您自己的域获取敏感信息,例如用户会话令牌。邪恶的开发人员可以创建一个提供有用服务的 API,然后使用该 API 从网站检索大量会话令牌(可以通过标头轻松找到原始网站Referer)。

您在不同端口上观察到的行为localhost是正常的,因为 cookie 不考虑端口,这是“出于历史原因”(仅供参考:HTTP cookie 端口是否特定?

所以留给你的选择是:

  • 将 cookie 设置domain为父域
  • 考虑到您的服务器可以使用标头而不是 cookie,因此根本不要使用 cookie(例如,使用带有 javascript 的 localStorage 和 HTTP 标头)
  • 考虑到您掌握基础设施,对 UI 和 API 使用单个域,并在服务器端进行一些 URL 重写(例如:以 开头的传入请求/api/...使用本地 API URL 重写,其他请求使用本地 UI URL 重写)