To prevent CSRF attacks that can spoof an authenticated user and execute critical transactions
defmodule TransactionController do
use MyApp.Web, :controller
def make_transaction(conn, %{'amount' => amount, 'recipient' => recipient}) do
# perform transaction...
end
end
In the insecure code example, the
make_transaction
function handles a transaction without validating a CSRF token. This allows an attacker to create a button with the content of a request and trick a user running a transaction to receive the app push notification and complete the request.
defmodule TransactionController do
use MyApp.Web, :controller
def make_transaction(conn, %{'_csrf_token' => csrf_token, 'amount' => amount, 'recipient' => recipient}) do
if Plug.CSRFProtection.check_csrf_token(conn, csrf_token) do
# perform transaction...
else
send_resp(conn, 403, "Invalid CSRF token")
end
end
end
In the secure code example, the
make_transaction
function validates the CSRF token using
Plug.CSRFProtection.check_csrf_token/2
. This ensures that the request is made by a legitimate user, preventing CSRF attacks.