Hello everyone,
I am trying to read a cookie I put on the connection after login. I set it like this…
defp put_refresh_cookie(conn, token) do
conn
|> put_resp_cookie("refresh", token, sign: true, http_only: true, secure: true, max_age: 604800)
# |> put_resp_cookie("refresh", token, sign: false, http_only: true, secure: true, max_age: 604800)
end
and I try to read it back in a refresh action of an API controller with…
refresh_cookie = conn.req_cookies["refresh"]
If I use sign: false in put_resp_cookie, I can read it back without problem. With sign: true, the value is not equivalent
How can I read it back when using sign: true?
Thanks in advance
The trick is mentioned in the docs for put_resp_cookie - the corresponding fetch_cookies call needs to specify which cookies are signed/encrypted.
For instance, here’s a spot that does it in phx.gen.auth’s code:
Thank You for your response…
I saw this fetch_cookies and used this code
conn = fetch_cookies(conn, signed: ~w(refresh))
refresh_cookie = conn.req_cookies["refresh"]
IO.inspect refresh_cookie, label: "COOKIE"
TokenHelpers.verify_token(refresh_cookie)
|> IO.inspect(label: "VERIFY")
But it does not seems to return the same value as passed, and when I verify the token, it fails
This is the token I pass
TOKEN: "SFMyNTY.g2gDdAAAAAJ3AmlkbQAAACRmYWMyZWU2MC0wMjRkLTQwOWItYmYxNi1kMTUxNmI4ZmFhNTl3BG5hbWVtAAAABWFkbWlubgYAUnkQEI4BYgABUYA.P0wcEGTxqV5_X-7JDOybsJ1oVzXfsFc2erYPKVxH7_g"
VERIFY: {:ok, %{id: "fac2ee60-024d-409b-bf16-d1516b8faa59", name: "admin"}}
This is the value I receive as the cookie
AFTER COOKIE: "SFMyNTY.g2gDbQAAAKNTRk15TlRZLmcyZ0RkQUFBQUFKM0FtbGtiUUFBQUNSbVlXTXlaV1UyTUMwd01qUmtMVFF3T1dJdFltWXhOaTFrTVRVeE5tSTRabUZoTlRsM0JHNWhiV1Z0QUFBQUJXRmtiV2x1YmdZQVVua1FFSTRCWWdBQlVZQS5QMHdjRUdUeHFWNV9YLTdKRE95YnNKMW9Welhmc0ZjMmVyWVBLVnhIN19nbgYAUnkQEI4BYgAJOoA.anW9pNkQ8yNy_bzRYl2RyKtIU2w_F2z1by9JfV8n-eo"
VERIFY: {:error, :invalid}
I will look at the phx.gen.auth code to see how they do
I need to get the cookie like this
refresh_cookie = conn.cookies["refresh"]
and not like this…
refresh_cookie = conn.req_cookies["refresh"]
I thought it would be the same, but it’s not.
Thank You for the help