Cors SET-COOKIE标头

时间:2020-09-22 14:37:12

标签: authentication cross-domain setcookie samesite

由丹尼尔·W回答。

My mistake was that I was calling a HTTP server endpoint instead of it's HTTPS version.

其他问题触及同一主题,但所有尝试都无法解决问题。

我的问题:

我无法从第二个JS客户端登录:

  • https:// localhost:4433正常工作(SET-COOKIE标头存在并且设置了cookie)
  • https:// localhost不起作用(SET-COOKIE标头存在,但未设置cookie)

登录端点:

http:// localhost:8000 / home / login

响应标题:

    Set-Cookie: .AspNetCore.Cookies=SomeCookieHere; expires=Sun, 10 Sep 2022 14:12:52 GMT; path=/; secure; samesite=none; httponly

JavaScript:

    $.post({
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        type: 'POST',
        url: 'http://localhost:8000/home/login', 
        data: {"userName":"userName","password":"password"},
        contentType: "application/x-www-form-urlencoded",
        dataType: "text/html",
        success: function(data) {}
    });

C#:

    authBuilder.AddCookie(options =>
    {
        options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.LoginPath = new PathString("/");
    })

1 个答案:

答案 0 :(得分:1)

您不能在非安全上下文中设置安全Cookie:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

具有Secure属性的cookie仅通过基于HTTPS协议的加密请求发送到服务器,而不会通过不安全的HTTP发送到服务器,因此中间人攻击者无法轻松访问。不安全的网站(URL中带有http :)无法使用Secure属性设置Cookie。

$.post({
    // url: 'http://localhost:8000/home/login', // Can't use HTTP endpoint
    url: 'https://localhost:4433/home/login', // This works
});