NodeJS “尝试通过Set-cookie标头设置cookie被阻止”问题,堆栈(ExpressJS、ReactJS、PassportJS)

but5z9lq  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(1306)

我正在用Passport JS实现Google身份验证。在localhost上一切都很好,但是在生产中遇到了一个问题。
My backend is deployed on render.com My frontend is deployed on vercel.app
由于This attempt to set a cookie via a Set-cookie header was blocked because its Domain attribute was invalid with regards to the current host url,未在前端设置Cookie
以下是我的快速会话配置:

const domain = process.env.DOMAIN;

domain is gotten from render.com environment variables: DOMAIN = review-website-mu.vercel.app
以编程方式设置Cookie配置:

if (domain) cookiesConfigs = {
        domain: domain,
        sameSite: 'none', 
        secure: false
    }

设置会话配置:

app.use(session({
    secret:'review-website',
    resave: false,
    saveUninitialized: false,
    store: new sessionStore({db: 'sessions.db', dir: './'}),
    cookie: cookiesConfigs
}));

问题是这样的:
error while setting cookies
我的域名:my domain
setCookie header
empty application cookies storage
如何修复并让我的应用在正面设置Cookie?
域名与前端的域完全相同,但它仍然不起作用

egmofgnx

egmofgnx1#

所以,经过几个小时的研究这个问题,我得出了下一个信息:
According to the RFC 6265 HTTP State Management Mechanism and exactly 4.1.2.3 "The Domain Attribute":

[...] The user agent will reject cookies unless the Domain attribute
      specifies a scope for the cookie that would include the origin
      server.
[...]  For example, the user agent will accept a cookie with a
       Domain attribute of "example.com" or of "foo.example.com" from
       foo.example.com, but the user agent will not accept a cookie with a
       Domain attribute of "bar.example.com" or of "baz.foo.example.com".
[...] NOTE: For security reasons, many user agents are configured to reject
      Domain attributes that correspond to "public suffixes".

第一步是将我的前端和后端都托管在同一个托管(render.com)上,但这根本不起作用。
首先,因为我的应用程序的前端和后端位于不同的子域上,这与上面的引用不匹配。(因此,如果前端是mysite.com,后端是api.mysite.com,但不是frontend.mysite.comapi.mysite.com,它将工作)。
其次,onrender.com在公共后缀列表中,所以无论这个域是否在那个列表中,你都不能通过域属性设置cookie。这里的解决方案是购买你自己的自定义域,并根据我上面写的要点设置它。
最后,我的解决方案是在cookie配置中省略the domain attribute,但保留Samesite: 'none'Secure属性。我仍然没有在我的前端cookie存储中看到cookie,但它不知何故工作。

if (domain) cookiesConfigs = {
        sameSite: 'none', 
        secure: true (or false, it doesn't matter here)
    }

相关问题