Insecurely Generated Token - JWT
Need
To ensure tokens are generated securely, preventing unauthorized access
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
def sign(user) do
jwt = %{id: user.id}
secret = 'weak-secret'
{:ok, token, _claims} = Guardian.encode_and_sign(jwt, secret)
token
end
This insecure code example shows a JWT token being signed with a weak secret key. This weak key can be easily cracked, allowing attackers to generate their own tokens, modify token parameters and access the service illegitimately.
Steps
- Use a strong secret key for JWT signing and verification
- Consider using environment variables to store the secret key securely
- Consider using a library or service that can generate strong secret keys
Compliant code
def sign(user) do
jwt = %{id: user.id}
secret = System.get_env('JWT_SECRET')
{:ok, token, _claims} = Guardian.encode_and_sign(jwt, secret)
token
end
This secure code example replaces the weak secret key with a strong secret key stored in an environment variable. This enhances the security of the JWT signing and verification process.