Blog | G5 Cyber Security

Fix Back Button Issues with CSRF Tokens

TL;DR

The back button can sometimes cause problems after submitting a form if your website uses CSRF (Cross-Site Request Forgery) tokens. This is because the token changes each session, and going back to the form might use an old, invalid token. This guide explains how to prevent this issue.

Understanding the Problem

When you submit a form, your website usually generates a unique CSRF token to protect against malicious attacks. If you hit the back button after submitting, the browser re-submits the original request with its old token. The server will likely reject this because the token no longer matches.

Solution: Prevent Re-Submission

  1. Prevent Caching of POST Requests:
    The most effective solution is to tell the browser not to cache the POST request that submits your form. This ensures it doesn’t try to re-submit the old data when you hit back.
    • Using HTTP Headers: Add these headers to your server response after a successful form submission:
      Cache-Control: no-cache, no-store, must-revalidate
      Pragma: no-cache
      Expires: 0
  2. Redirect After Submission (Recommended):
    Instead of letting the user stay on the same page after submitting, immediately redirect them to a different page. This breaks the back button’s ability to re-submit the form.
    • Example PHP:
      header('Location: /thank-you');
  3. Check Token on Back Button Navigation (More Complex):
    If you *must* allow the user to stay on the same page, you can try to detect if they’re navigating back and re-validate the token.
    • JavaScript Detection: Use JavaScript to check the history.length property. If it increases after a form submission, it likely means the user is going forward in history (normal navigation). If it decreases, they are going back.
      if (window.history.length > 1) {
        // User is navigating forward - normal behaviour
      } else {
        // User is going back - potentially re-submitting form, check token!
      }
    • Token Re-validation: If the user is navigating back, you’ll need to fetch a new CSRF token (using AJAX) and update the hidden field in your form before allowing submission. This requires JavaScript.

Important Considerations

Exit mobile version