Prevent reuse of expired session tokens to ensure session integrity
defmodule MyAppWeb.Endpoint do
use Guardian.Plug.VerifyHeader, realm: "Bearer"
def call(conn, _) do
case Guardian.Plug.current_token(conn) do
nil -> conn
token ->
if MyApp.Auth.Token.is_expired?(token) do
MyApp.Auth.Token.extend_expiration(token)
end
conn
end
end
end
This example depicts an API endpoint in a Phoenix application that authenticates the user using JWT tokens generated with the Guardian library. The problem lies in the token validation mechanism, where the code checks the token's expiration date against the current time but does not verify if the token itself is expired.
defmodule MyAppWeb.Endpoint do
use Guardian.Plug.VerifyHeader, realm: "Bearer"
def call(conn, _) do
case Guardian.Plug.current_token(conn) do
nil -> conn
token ->
if MyApp.Auth.Token.is_expired?(token) do
conn
|> put_status(:unauthorized)
|> Phoenix.Controller.json(%{error: "Expired token"})
|> halt()
end
conn
end
end
end
In the fixed code, the token extension functionality has been removed. Therefore, once a token has expired, it can no longer be used, ensuring the integrity of the session.