CSRF Protection

What is CSRF?

Cross-Site Request Forgery (CSRF) is an attack that forces an authenticated user to execute unwanted actions on a web application. If a user is authenticated to your site, an attacker can trick their browser into making requests to your application on their behalf.

For example, imagine a user is logged into your banking application. They then visit a malicious website that contains this hidden form:

<form action="https://yourbank.com/transfer" method="POST" id="evil">
    <input type="hidden" name="to" value="attacker-account">
    <input type="hidden" name="amount" value="10000">
</form>
<script>document.getElementById('evil').submit();</script>

Because the user is already authenticated (their browser has the session cookie), this request would succeed unless you have CSRF protection in place.

How UserFrosting Protects Against CSRF

UserFrosting uses CSRF tokens to protect against these attacks. A CSRF token is a unique, secret value generated by the server and tied to the user's session. When a form is submitted or an AJAX request is made, the token must be included in the request. The server validates that the token matches what it expects for that session.

We'll see in a later chapter how to include CSRF tokens in your forms and AJAX requests.

When CSRF Protection Applies ?

CSRF protection is relevant to:

  • POST requests
  • PUT requests
  • DELETE requests
  • PATCH requests

GET requests are not protected, as they shouldn't modify state anyway.

If a CSRF token is missing or invalid, the system should reject the request with a 400 Bad Request error. This protects your application but means you need to ensure:

  1. Every form includes the CSRF token
  2. AJAX requests include the token in the payload
  3. Tokens are refreshed if sessions expire
  4. Single-page applications properly manage token lifecycle

Warning

Never disable CSRF protection in production. If you're having issues with CSRF validation, fix the root cause rather than disabling this critical security feature.

For stateless APIs that use token-based authentication (like OAuth or JWT), CSRF protection is typically not needed because there are no cookies involved. However, if your API endpoints rely on session cookies for authentication, CSRF protection is essential.