Skip to content

Commit

Permalink
Avoid fixation attacks by renewing session ID (#72)
Browse files Browse the repository at this point in the history
* Use `residentKey` instead of `requireResidentKey`

* typo

* provide requireResidentKey as well, just in case

* Set require true only when r.key == required

* Avoid fixation attacks by renewing session ID

* delete CSRF token when renewing session

---------

Co-authored-by: Owen Bickford <[email protected]>
  • Loading branch information
peaceful-james and type1fool authored Jul 11, 2024
1 parent 38a1253 commit 9639617
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions templates/controllers/session.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ defmodule <%= inspect @web_pascal_case %>.Session do
else
_error ->
conn
|> clear_session()
|> renew_session()
end
end

Expand All @@ -32,7 +32,7 @@ defmodule <%= inspect @web_pascal_case %>.Session do

{:error, _} ->
conn
|> clear_session()
|> renew_session()
|> put_flash(:error, "Please sign in.")
|> redirect(to: ~p"/sign-in")
end
Expand All @@ -44,8 +44,31 @@ defmodule <%= inspect @web_pascal_case %>.Session do
|> Identity.delete_all_user_sessions()

conn
|> clear_session()
|> renew_session()
|> put_flash(:info, "Successfully signed out.")
|> redirect(to: ~p"/")
end

# This function renews the session ID and erases the whole
# session to avoid fixation attacks. If there is any data
# in the session you may want to preserve after log in/log out,
# you must explicitly fetch the session data before clearing
# and then immediately set it after clearing, for example:
#
# defp renew_session(conn) do
# preferred_locale = get_session(conn, :preferred_locale)
#
# conn
# |> configure_session(renew: true)
# |> clear_session()
# |> put_session(:preferred_locale, preferred_locale)
# end
#
defp renew_session(conn) do
delete_csrf_token()

conn
|> configure_session(renew: true)
|> clear_session()
end
end

0 comments on commit 9639617

Please sign in to comment.