Questions about Phoenix.Token

I have implemented it for API authentication but I have some questions regarding it.

a. What is the default TTL for a Phoenix.Token and how to customize this setting?
b. How to verify the validity of a token sent by an end user server side?
c. Is it possible to revoke it server side?
d. What types of data can be encoded into the token and reused later? Real examples are welcome :slight_smile:

Thank you.

2 Likes

I am using these helpers to manage phoenix token

defmodule BlahWeb.TokenHelpers do
  @salt "blah salt"
  @max_age 86400
  
  @spec sign(term) :: String.t
  def sign(user), do:
    Phoenix.Token.sign(BlahWeb.Endpoint, @salt, user.id)
  
  @spec verify_token(String.t) :: {:ok, integer} | {:error, term}
  def verify_token(token), do:
    Phoenix.Token.verify(BlahWeb.Endpoint, @salt, token, max_age: @max_age)
end

As You can see

a) I use 86400 TTL
b) I use verify_token()
c) You would need to make something like guardian_db
d) Anything to identify the user server side without the need to make db call. That would mean user.id, maybe role_ids… Anyway, You cannot store something too big.

4 Likes

But if you did want to store/retrieve something big then rather than encoding the data directly in the token, you could create a new table in your DB in a table, for example a user_sessions table. Then in the token rather than storing just user.id as @kokolegorille does in the example above, you could store {user.id, session.id} (or just session.id) and then use the session.id to retrieve the data. This is generally more performant than sending a large session back with every request from the client.

5 Likes