To prevent unauthorized user data modifications by ensuring token's expiry time is reasonable
defmodule InsecureToken do
alias Guardian.JWT
@secret_key "Your secret key"
def create_token(claims) do
{:ok, token, _claims} = JWT.encode_and_sign(claims, key: @secret_key, ttl: {432000, :second})
token
end
end
In this code snippet, JWT tokens are created with a lifespan of approximately 5 days (represented as 432000 seconds). This is too long and it increases the risk that a malicious actor can use a stolen token for unauthorized activities.
defmodule SecureToken do
alias Guardian.JWT
@secret_key "Your secret key"
def create_token(claims) do
{:ok, token, _claims} = JWT.encode_and_sign(claims, key: @secret_key, ttl: {900, :second})
token
end
end
In the secure version of the code, the lifespan of the token has been significantly reduced to approximately 15 minutes (represented as 900 seconds). This reduces the time window for an attacker to use a stolen token.