Prevent session hijacking by securing session cookies.
defmodule MyApp.SessionController do
use MyApp, :controller
def create(conn, %{"user" => user_params}) do
case MyApp.Authenticator.authenticate(user_params) do
{:ok, user} ->
conn
|> put_session(:user_id, user.id)
|> redirect(to: "/welcome")
{:error, reason} ->
render(conn, "login.html", error: reason)
end
end
end
This Elixir/Phoenix code does not handle session cookies securely. The session cookie is not regenerated after login, which allows an attacker to fixate a session, and then hijack the user session once the victim logs in.
defmodule MyApp.SessionController do
use MyApp, :controller
def create(conn, %{"user" => user_params}) do
case MyApp.Authenticator.authenticate(user_params) do
{:ok, user} ->
conn
|> configure_session(renew: true)
|> put_session(:user_id, user.id)
|> redirect(to: "/welcome")
{:error, reason} ->
render(conn, "login.html", error: reason)
end
end
end
This secure Elixir/Phoenix code example regenerates the session cookie after a successful login. The call to 'configure_session(renew: true)' ensures a new session is created, preventing session fixation.