在凤凰中实现“记住我" [英] Implementing remember-me in phoenix

查看:79
本文介绍了在凤凰中实现“记住我"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初,我选择使用put_session来存储用户ID,因为无法篡改会话哈希.但是,似乎会话cookie仅在浏览器会话期间持续存在.当用户重新打开浏览器时,浏览器消失了,用户必须再次登录.

At first I chose to use put_session to store user id because session hash cannot be tampered. However it seems like session cookie only persist during the browser session. When the user re-opens the browser, it's gone and the user has to log in again.

我读到另一种选择可能是为每个用户生成一个安全的随机令牌,并将其存储在数据库中,然后将其放入具有高到期日期的常规Cookie中.但是,鉴于此cookie没有篡改保护AFAIK(但我可能是错的)并且连接并不总是https,我猜任何人在用户和服务器之间的中间监听http都可以劫持用户会话

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. 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.

因此,问题是如何以安全的方式在会话中保留用户ID?还是其他方式呢?

Hence the question is how can I persist user id in session in a secure way? Or what are the other ways?

推荐答案

默认cookie"max-age"直到关闭浏览器为止. 您应该给cookie一个非常高的"max_age"值: http://hexdocs.pm/plug/Plug.Conn.html#put_resp_cookie/4

The default cookie "max-age" is until close borwser. You should give the cookie a really high "max_age" value: http://hexdocs.pm/plug/Plug.Conn.html#put_resp_cookie/4

另一种设置"max_age"的方法,在官方文档中找不到,但是它有效:

Another way set "max_age", I can't find it in official doc,but it works:

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

这篇关于在凤凰中实现“记住我"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆