【问题标题】:ASP.NET Core Cookie not set with CORSASP.NET Core Cookie 未使用 CORS 设置
【发布时间】:2021-12-14 10:44:28
【问题描述】:

我尝试设置身份验证 cookie。 ui 和数据服务器在不同的子域下。所以我需要激活 CORS。

services.AddCors(options => options.AddPolicy("SubdomainDefault", builder => builder
     .WithOrigins("https://ui.domain.de")
     .AllowCredentials()
     .AllowAnyHeader()
     .Build()
));

在同一个子域上设置了 cookie,但对于不同的子域,它在标题中可见,但未设置。

Request URL: https://server2.domain.de/...
Request Method: POST
Status Code: 200 OK
Remote Address: X.X.X.X:443
Referrer Policy: strict-origin-when-cross-origin

Response Header
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://ui.domain.de
Content-Length: 1017
Content-Type: application/json; charset=utf-8
Date: Fri, 29 Oct 2021 10:27:11 GMT
Server: Microsoft-IIS/8.5
Set-Cookie: auth=XXX; domain=.domain.de; path=/; secure; samesite=strict; httponly
Vary: Origin
X-Powered-By: ARR/3.0

Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en;q=0.8,en-US;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 0
Host: server2.domain.de
Origin: https://ui.domain.de
Pragma: no-cache
Referer: https://ui.domain.de/
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36

有人有想法吗?

【问题讨论】:

    标签: asp.net-core cookies cross-domain


    【解决方案1】:

    假设您的第二个请求实际上是一个 XMLHttpRequest,您需要设置 withCredentials 标志,否则不会发送 cookie。

    这是https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#requests_with_credentials的摘录:

    const invocation = new XMLHttpRequest();
    const url = 'https://bar.other/resources/credentialed-content/';
    
    function callOtherDomain() {
      if (invocation) {
        invocation.open('GET', url, true);
        invocation.withCredentials = true;
        invocation.onreadystatechange = handler;
        invocation.send();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 2019-01-29
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多