Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Symfony form says: The CSRF token is invalid. Please try to resubmit the form

ErrorThe CSRF token is invalid. Please try to resubmit the form.

Short answer

Symfony rejects the form when the submitted token does not match the one it expects. Four causes cover most cases: the token id or field name differs between template and controller, the session was lost, a cache served an old page with another visitor's token, or stateless tokens fail the Origin check behind a proxy.

  • Applies to Symfony 7.3, PHP 8.3, Twig 3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Find out whether the failure is on every submit or only for some users or pages. Every submit points to an id or field mismatch; random failures point to sessions or caching. Then confirm that CSRF protection is on and which token ids are stateless.

    php bin/console debug:config framework csrf_protection
  2. 2Match what you see, then jump to its fix

    1. 1Every submit fails, including a fresh page loadThe token id or field name differs between the template and the checkFix
    2. 2The first submit after a long idle time fails, or it fails only on one browser or domainThe session is missing, expired or not sent backFix
    3. 3Fails only for some visitors, and the page comes back with a cache headerA full-page cache serves a form with someone else's tokenFix
    4. 4Only stateless token ids fail, and only on the production host behind a load balancerStateless tokens fail the Origin or Referer check behind a proxyFix

What does the error look like?

  • The CSRF token is invalid. Please try to resubmit the form.
  • Invalid CSRF token.

Cause 1 of 4

The token id or field name differs between the template and the check

1Check

The id given to csrf_token() in the template must be the one given to isCsrfTokenValid() or the IsCsrfTokenValid attribute. A per-item id such as 'delete-item-' ~ post.id needs an Expression in the attribute. The form field name must match on both sides too.

grep -rn "csrf_token(\|isCsrfTokenValid\|IsCsrfTokenValid\|csrf_token_id\|csrf_field_name" templates/ src/

2Fix

Use the same id and the same field name in both places. For a hand-written form:

{# template #}
<input type="hidden" name="token" value="{{ csrf_token('delete-item') }}">

// controller
if ($this->isCsrfTokenValid('delete-item', $request->request->get('token'))) {
    // safe to continue
}

3Verify

Load the page fresh and submit once; the action goes through.

php bin/console debug:router

Confirmed by symfony.com

Did this fix it?

Cause 2 of 4

The session is missing, expired or not sent back

1Check

By default the token is stored in the session, started when a CSRF-protected form is rendered. If the session is lost, expires or the cookie is not sent with the POST, the token cannot be checked. Symfony takes the session lifetime from session.gc_maxlifetime in php.ini unless you change it.

php bin/console debug:config framework session
php -i | grep session.gc_maxlifetime

2Fix

Make sure the page and the POST use the same host and scheme (cookie_secure: auto sends the cookie only over HTTPS), and that the session lifetime is longer than the time users take to fill the form.

; php.ini  (seconds)
session.gc_maxlifetime = 7200

3Verify

Wait, then submit again, or submit from the same domain as the page.

php bin/console debug:config framework session

Confirmed by symfony.com

Did this fix it?

Cause 3 of 4

A full-page cache serves a form with someone else's token

1Check

If a cache returns HTML that contains a token generated for another session, the submitted token will not match. Look at the response headers of the form page.

curl -sI https://example.com/contact | grep -i -E 'cache|age|x-'

2Fix

Do not cache pages with a token. Render the form in an uncached fragment (ESI or an AJAX request), or switch the form to stateless CSRF tokens, which suit cached pages.

# config/packages/csrf.yaml
framework:
    csrf_protection:
        stateless_token_ids: ['submit', 'authenticate', 'logout']

3Verify

Request the page twice from different browsers and submit the form from both.

curl -sI https://example.com/contact

Confirmed by symfony.com

Did this fix it?

Cause 4 of 4

Stateless tokens fail the Origin or Referer check behind a proxy

1Check

Stateless tokens are validated against the Origin or Referer header, which must match the application's domain. A misconfigured reverse proxy changes the host the app sees.

php bin/console debug:config framework trusted_proxies

2Fix

Configure Symfony to trust the proxy and its forwarded headers as the load balancer documentation describes.

# config/packages/framework.yaml
framework:
    trusted_proxies: '%env(TRUSTED_PROXIES)%'
    trusted_headers: ['x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-port']

3Verify

Submit the form on the production host again.

php bin/console cache:clear

Confirmed by symfony.com

Did this fix it?

How do I stop it coming back?

  • Give each form its own token id, and keep it in one constant used by both the template and the controller.
  • Do not full-page cache any page that has a token unless the form is loaded as an uncached fragment or uses stateless tokens.
  • Turn off CSRF only on read-only GET forms, and do it for that form, not globally.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Apache returns 403 when a URL contains %3F

a request like /page%3Fname=test is refused while /page?name=test works

Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.

2 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.