logo

Insecurely Generated Token - JWT - Elixir


Need

To ensure tokens are generated securely, preventing unauthorized access


Context

  1. Usage of Elixir 1.12 for functional programming and building scalable applications
  2. Usage of Phoenix Framework 1.6 for web development
  3. Usage of Guardian 2.0 for authentication and authorization

Description

Insecure Code Example

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

  1. Use a strong secret key for JWT signing and verification
  2. Consider using environment variables to store the secret key securely
  3. Consider using a library or service that can generate strong secret keys

Secure Code Example

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.


References

  • 309 - Insecurely Generated Token - JWT

  • Last updated

    2023/09/18