简体   繁体   English

即使响应标头中存在cookie,浏览器也不会设置cookie

[英]Browser doesn't set cookie even if it is present in response headers

My response has a set-cookie header present but the browser doesn't seem to store it (in postman it works like a charm). 我的回复有一个set-cookie标题,但浏览器似乎没有存储它(在postman中它就像一个魅力)。 My API is written in .NET Core, and im using axios (React) on the client. 我的API是用.NET Core编写的,我在客户端使用axios(React)。 The client requests are, however, proxied through an express server for SSR purposes. 但是,客户端请求通过快速服务器进行代理以用于SSR目的。

I have tried multiple solutions posted here. 我在这里发布了多个解决方案。 From the basics of setting withCredentials to true in axios to setting the MinimumSameSitePolicy on the server to none which can be seen in the code. 从设置withCredentials的基础到axios中的true,将服务器上的MinimumSameSitePolicy设置为none,可以在代码中看到。

Server 服务器

services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.HttpOnly = false;
            });
..........
 app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None,
                HttpOnly = HttpOnlyPolicy.None
            });

Client 客户

const axiosInstance = axios.create({
  baseURL: '/api',
  withCredentials: true,
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Content-Type': 'application/json'
  }
});

Proxy 代理

app.use(
  '/api',
  proxy('https://localhost:44364/', {
    proxyReqOptDecorator(opts) {
      opts.rejectUnauthorized = false;
      opts.headers['x-forwarded-host'] = 'localhost:3000';
      return opts;
    },
    proxyReqPathResolver(req) {
      return `/api${req.url}`;
    }
  })
);

The response with cookie: 对cookie的回复:

HTTP/1.1 200 OK
x-powered-by: ASP.NET
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
expires: Thu, 01 Jan 1970 00:00:00 GMT
server: Kestrel
set-cookie: .AspNetCore.Cookies=CfDJ8KvV0sFM8_FJqzJkoUey_LvYSADPHUA20Mq40db0KYSbL9Q2ZjS2JW87G8CzcTDBIpG1H6mZ_nuThzOniga7oRpguIgi3xIFCjkY5D0DXwT98ZVejY7nzLaCmV9rGLMkkqqADbr0zzwUkzXQqtWMtubY0cdHXPskTWFucMjjYk0BU4eCuWOjRzooL-QtwYtDClP720LVetm8lZGvAS6jfYpk-HWZIQiDo1ERKqhyIWKYqSFBEN0nV4ykL6KhfqEjcK8URzTEnBxdV7dCpk287smjAzTvOziRWfO6BtpxXC2tZ9NBeTLLqitn_CaAypewt9qMnjMi75zazo6yicRlTsDp-i3LT0OkD_ls1celSeG1VPlTg0OMVm0nADpZurMT9LSrijsSrcFT0wvNSTeW9vE; path=/; secure; samesite=lax; httponly
x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWFrYWxhXERlc2t0b3BcUm91dG9yaWFsXFJvdXRvcmlhbEFQSVxSb3V0b3JpYWxBUElcUm91dG9yaWFsQVBJXGFwaVxhY2NvdW50XGxvZ2luU3VibWl0?=
date: Sun, 26 May 2019 15:47:32 GMT
connection: close
Content-Length: 6
ETag: W/"6-+3OfqLi6+pGCkKvbVPPQANDiBD4"

In version 2.0, asp.net core introduced a new behavior: by default it adds a samesite=lax attribute to all set-cookie headers. 在2.0版本中,asp.net核心引入了一种新行为:默认情况下,它会向所有set-cookie标头添加samesite=lax属性。

The Cookie Policy Middleware setting for MinimumSameSitePolicy can affect your setting of Cookie.SameSite in CookieAuthenticationOptions MinimumSameSitePolicy的Cookie策略中间件设置可能会影响Cookie.SameSiteCookieAuthenticationOptions设置

Try to explicitly override this default behavior in Startup.ConfigureServices: 尝试在Startup.ConfigureServices中显式覆盖此默认行为:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options => options.Cookie.SameSite = SameSiteMode.None;
            });

Refer to: AspNet Core Identity, how set options.Cookie.SameSite? 请参阅: AspNet Core Identity,如何设置options.Cookie.SameSite?

Thanks @Xing Zou! 谢谢@Xing Zou! Your answer was close and made me think in the right direction. 你的答案很接近,让我思考正确的方向。 The CookiePolicyOptions were not working at all and didn't seem to override the default options. CookiePolicyOptions根本不起作用,似乎没有覆盖默认选项。 Instead, I used 相反,我用过

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
             options.Cookie.SameSite = SameSiteMode.None;
             options.Cookie.HttpOnly = true;
             options.Cookie.SecurePolicy = CookieSecurePolicy.None;
        });

in ConfigureServices and 在ConfigureServices和

 app.UseAuthentication();

in Configure. 在配置中。

The browser wasnt setting the cookie when it had the secure flag so it had to be disabled with 当浏览器具有安全标志时,浏览器没有设置cookie,因此必须禁用它

options.Cookie.SecurePolicy = CookieSecurePolicy.None;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM