To ensure tokens are generated securely, preventing unauthorized access
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.
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.