Insecurely Generated Token - Lifespan
Need
To prevent unauthorized user data modifications by ensuring token's expiry time is reasonable
Context
- Usage of Elixir 1.12 for functional programming and building scalable applications
- Usage of Phoenix Framework 1.6 for web development
- Usage of Guardian 2.0 for authentication and authorization
Description
Non compliant code
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.
Steps
- Reduce the lifespan of JWT tokens to a more reasonable timeframe
- Invalidate tokens on the server side when a user logs out
- Consider token refresh strategies if long-lived tokens are required
Compliant code
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.