Read http only cookie server side

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

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

1 Like

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

VERIFY: {:ok, %{id: "fac2ee60-024d-409b-bf16-d1516b8faa59", name: "admin"}}

This is the value I receive as the cookie

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