Cookies在官方的SvelteKit示例中使用–host选项运行时未被设置。

huangapple go评论77阅读模式
英文:

Cookies are not getting set when running with --host option in official SvelteKit example

问题

以下是翻译好的部分:

"我正在尝试官方的 SvelteKit 示例 https://realworld.svelte.dev/。"
"其代码托管在 https://github.com/sveltejs/realworld 上。"
"当我运行 npm run dev 时,登录和一切都正常工作。"
"但是当我运行 npm run dev -- --host 时,登录不起作用。"
"这段代码不起作用,因此无法设置 cookie,所以登录无法正常工作。"
"如何在使用 --host 选项时使登录正常工作?"

英文:

I am trying offical SvelteKit example https://realworld.svelte.dev/.
Its code is hosted at https://github.com/sveltejs/realworld

login and everything works fine when I run npm run dev
but when I run npm run dev -- --host then login does not work.

cookies.set('jwt', value, { path: '/' });

This is not working so cookies are not getting set so login is not working.

How can I make login working when using --host option?

答案1

得分: 6

我假设在使用未安全连接(http)时,当访问暴露的网络IP URL(localhost仍然可用)时,您无法登录。

这是因为SvelteKit中默认的cookie配置是将secure选项设置为true,这意味着在未安全的请求上不会设置cookie。根据SvelteKit文档

> httpOnly和secure选项默认为true(除了在http://localhost上,其中secure为false),如果要使cookie可供客户端JavaScript读取和/或通过HTTP传输,必须明确禁用这些选项。sameSite选项默认为lax。

正如您所看到的,这解释了为什么默认配置在localhost上运行正常(其中securefalse),但在暴露的网络IP地址上不起作用(其中secure将为true)。

如果您在src/routes/login/+page.server.js中更新cookie配置以明确设置secure选项:

cookies.set('jwt', value, { secure: false, path: '/' });

然后重新启动服务器,您应该能够如预期地从暴露的网络IP URL登录(我成功登录了)。

注意: 在生产部署中,您希望将secure标志设置为true并使用安全协议(https)进行请求。

英文:

I'm assuming you're blocked from logging in when addressing the exposed network IP URL (localhost should still work) on an unsecured (http) connexion.

The reason for this is because the default cookie configuration in SvelteKit is to set the secure option to true, meaning cookies won't get set upon unsecured requests. From the SvelteKit docs:

> The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.

As you can see, this explains why the default configuration works on localhost (where secure is false) but not on the exposed network IP address (where secure will be true).

If you update the cookie configuration in src/routes/login/+page.server.js to explicitly set the secure option:

cookies.set('jwt', value, { secure: false, path: '/' });

and restart your server, you should then be able to login as expected from the exposed network IP URL (I was able to).

Note: in a production deployment, you will want the secure flag set to true and use a secure protocol (https) for your requests.

huangapple
  • 本文由 发表于 2023年1月8日 09:46:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75045021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定