简体   繁体   English

在凤凰中实现记住我

[英]Implementing remember-me in phoenix

At first I chose to use put_session to store user id because session hash cannot be tampered. 起初我选择使用put_session来存储用户ID,因为会话哈希不能被篡改。 However it seems like session cookie only persist during the browser session. 然而,似乎会话cookie仅在浏览器会话期间持续存在。 When the user re-opens the browser, it's gone and the user has to log in again. 当用户重新打开浏览器时,它已经消失,用户必须再次登录。

I read that another option might be to generate a secure random token for each user and store it in the database and put it in a regular cookie with high expiration date. 我读到另一种选择可能是为每个用户生成一个安全的随机令牌,并将其存储在数据库中,并将其放入具有高到期日期的常规cookie中。 However, given that this cookie doesn't have tampering protection AFAIK (but I might be wrong) and connection is not always https, I guess anyone listening to http in the middle between the user and the server would be able to hijack the user session. 然而,由于这个cookie没有篡改保护AFAIK(但我可能是错的),并连接不总是HTTPS,我想任何人听在用户和服务器之间的中间到http将能够劫持用户会话。

Hence the question is how can I persist user id in session in a secure way? 因此,问题是如何以安全的方式在会话中持久保存用户ID? Or what are the other ways? 或者其他方式是什么?

The default cookie "max-age" is until close borwser. 默认cookie“max-age”直到close borwser。 You should give the cookie a really high "max_age" value: http://hexdocs.pm/plug/Plug.Conn.html#put_resp_cookie/4 你应该给cookie一个非常高的“max_age”值: http ://hexdocs.pm/plug/Plug.Conn.html#put_resp_cookie/4


Another way set "max_age", I can't find it in official doc,but it works: 设置“max_age”的另一种方法,我在官方文档中找不到它,但它有效:

defmodule HelloPhoenix.Endpoint do
  use Phoenix.Endpoint, otp_app: :hello_phoenix
. . .
  plug Plug.Session,
    store: :cookie,
    key: "_hello_phoenix_key",
    signing_salt: "Jk7pxAMf",
    max_age: 2592000 # 60*60*24*30
. . .
end

I'm implementing "Remember me" on my site. 我正在我的网站上实施“记住我”。 Using Phoenix.Token, the cookie can be read by clients. 使用Phoenix.Token,客户端可以读取cookie。 So I use MessageEncryptor ( https://github.com/elixir-lang/plug/blob/master/lib/plug/crypto/message_encryptor.ex ) to encrypt and sign the ticket. 所以我使用MessageEncryptor( https://github.com/elixir-lang/plug/blob/master/lib/plug/crypto/message_encryptor.ex )来加密和签署故障单。 Then I use put_resp_cookie with a high max-age to put the encrypted ticket to cookie. 然后我使用具有高max-age的put_resp_cookie将加密的票证放入cookie。 Please note that IE doesn't support max-age so "Remember me" won't work on IE. 请注意,IE不支持max-age,因此“记住我”将无法在IE上运行。

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

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