Prevent unauthorized modification of session cookies
defmodule SessionController do
use MyApp.Web, :controller
def set_session(conn, %{'session' => session_params}) do
conn
|> put_session(:user_id, session_params["user_id"])
|> send_resp(200, "Session has been set")
end
end
In this code, the session value is set based on whatever value is received from the user, without any validation. This allows an attacker to set an arbitrary value for the user_id in the session, potentially impersonating another user.
defmodule SessionController do
use MyApp.Web, :controller
def set_session(conn, %{'session' => session_params}) do
if valid_session_params?(session_params) do
conn
|> put_session(:user_id, session_params["user_id"])
|> send_resp(200, "Session has been set")
else
send_resp(conn, 400, "Invalid session parameters")
end
end
defp valid_session_params?(session_params) do
# Implement validation logic here
end
end
In the secure code example, the session parameters are validated before they are used to set the session. If the parameters are not valid, an error response is returned. This prevents an attacker from setting an arbitrary session value.