Create secure, unpredictable session tokens to prevent reuse
defmodule InsecureToken do
def generate_token(user_id) do
user_id
|> Integer.to_string
|> String.reverse
end
end
The
generate_token
function is insecure because it simply reverses the user_id and uses it as a token. This approach is predictable and can easily be reverse-engineered, which could allow an attacker to reuse a session token after 14 days.
defmodule SecureToken do
@secret_key_base "s3cr3t"
def generate_token(user_id) do
Phoenix.Token.sign(@secret_key_base, "user salt", user_id)
end
def verify_token(token, user_id) do
Phoenix.Token.verify(@secret_key_base, "user salt", token, max_age: 14 * 24 * 60 * 60)
end
end
The
generate_token
function now uses
Phoenix.Token.sign/3
to generate a secure token, and
verify_token
uses
Phoenix.Token.verify/4
to verify the token's integrity and timeliness. The token is cryptographically secure and unpredictable, and it cannot be reused after 14 days.