Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing remember-me in phoenix

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.

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.

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

like image 758
ave Avatar asked Jan 03 '16 15:01

ave


2 Answers

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


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
like image 193
Lei Wang Avatar answered Oct 01 '22 20:10

Lei Wang


I'm implementing "Remember me" on my site. Using Phoenix.Token, the cookie can be read by clients. So I use MessageEncryptor (https://github.com/elixir-lang/plug/blob/master/lib/plug/crypto/message_encryptor.ex) to encrypt and sign the ticket. Then I use put_resp_cookie with a high max-age to put the encrypted ticket to cookie. Please note that IE doesn't support max-age so "Remember me" won't work on IE.

like image 44
hai tran ba Avatar answered Oct 01 '22 19:10

hai tran ba