To ensure the integrity and validity of JWT access tokens used for authentication.
defmodule MyAppWeb.TokenController do
use MyAppWeb, :controller
def verify_token(conn, %{"token" => token}) do
{:ok, _} = JOSE.JWT.decode(token)
send_resp(conn, 200, "Token is valid")
end
end
In this insecure code example, the JWT token is decoded, but its signature is not validated. This means that an attacker could modify the payload of the token, or even remove the signature entirely, and the server would still accept it as valid.
defmodule MyAppWeb.TokenController do
use MyAppWeb, :controller
def verify_token(conn, %{"token" => token}) do
case JOSE.JWT.verify_strict(token, ["HS256"], "secret") do
{true, _, _} ->
send_resp(conn, 200, "Token is valid")
_ ->
send_resp(conn, 401, "Invalid token")
end
end
end
In this secure code example, the application correctly verifies the JWT token using the JOSE.JWT.verify_strict function with the appropriate algorithm and secret key. This prevents attackers from modifying the token payload or removing the signature.