[英]Sending HTTPOnly cookie in response using Rails API application
Correct me if I'm wrong but cookies are just special Set-Cookie:
headers, right?如果我错了,请纠正我,但 cookie 只是特殊的
Set-Cookie:
标题,对吗? Maybe I'm missing something but that always seemed like the case to me.也许我错过了一些东西,但对我来说似乎总是如此。 If I set up a Rails API application and want to support sending HTTPOnly cookies (eg headers also assume I've got CORS and everything on the client setup etc) I should be able to do this correct?
如果我设置了一个 Rails API 应用程序并希望支持发送 HTTPOnly cookie(例如,标头也假设我有 CORS 以及客户端设置等上的所有内容),我应该能够正确地做到这一点吗?
Basically, my questions are these:基本上,我的问题是这些:
ActionDispatch::Cookies
into my middleware and adding include ::ActionController::Cookies
in my application controller totally defeat the purpose of an API application?ActionDispatch::Cookies
带回我的中间件并在我的应用程序控制器中添加include ::ActionController::Cookies
完全违背了 API 应用程序的目的?So I don't need to add back any middleware or include any classes for cookies.所以我不需要添加任何中间件或包含任何 cookie 类。 I can use
reponse.set_header
to send a cookie.我可以使用
reponse.set_header
发送cookie。 However, this only lets you send one Set-Cookie
header because it will overwrite the last header you set with Set-Cookie
as the key.但是,这只允许您发送一个
Set-Cookie
标头,因为它会覆盖您使用Set-Cookie
作为键Set-Cookie
的最后一个标头。 Instead you have access to response.set_cookie
which will let you set multiple cookies with each set_cookie
call.相反,您可以访问
response.set_cookie
,它可以让您在每个set_cookie
调用中设置多个 cookie。 It also comes with some options that you can set that you would have to add to the value of the header you were sending manually with set_header
.它还带有一些您可以设置的选项,您必须将这些选项添加到您使用
set_header
手动发送的标头的值中。
Here's an example I used that allowed me to send a cookie:这是我使用的一个示例,它允许我发送 cookie:
response.set_cookie(
:jwt,
{
value: 'this could be a token or whatever cookie value you wanted.',
expires: 7.days.from_now,
path: '/api/v1/auth',
httponly: true
}
)
Check the documentation for this method for other options because there are others.检查此方法的文档以获取其他选项,因为还有其他选项。
EDIT: I was having an issue where the cookie was getting sent in the response but not saved (still).编辑:我遇到了一个问题,cookie 在响应中被发送但没有保存(仍然)。 It wasn't showing up in the cookie storage so I changed the path of the cookie getting sent to
/
and then it showed up.它没有出现在 cookie 存储中,所以我更改了发送到
/
的 cookie 的路径,然后它出现了。 I deleted it and then changed the cookie's path to /my/real/path
and it worked and was stored in cookie storage.我删除了它,然后将 cookie 的路径更改为
/my/real/path
并且它工作并存储在 cookie 存储中。 Go figure.去搞清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.