Skip to main content

Insecurely Generated Token - Validation

Need

To prevent unauthorized user creation and protect the integrity of user data

Context

  • Usage of Elixir 1.12 for building scalable and fault-tolerant 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

def decode_and_verify(token) do
{:ok, claims} = JWT.decode_and_verify(token)
IO.inspect(claims)
end
end

In this code snippet, a JWT token is decoded without verifying its signature, thus allowing tampering. An attacker can modify the token header, to change the algorithm used for signature and create users without the token being properly validated.

Steps

  • Ensure that the JWT token signature is properly validated before decoding
  • Use a known and secure algorithm for token encryption
  • Consider using a library like Guardian for Elixir that provides secure handling of JWT tokens

Compliant code

defmodule SecureToken do
alias Guardian.JWT
@secret_key "Your secret key"

def decode_and_verify(token) do
{:ok, claims} = JWT.decode_and_verify(token, key: @secret_key)
IO.inspect(claims)
end
end

In the secure version of the code, the token is decoded and verified with a predefined secret key. This ensures the token's integrity and authenticity, thus preventing the creation of unauthorized users.

References