Symfony form says: The CSRF token is invalid. Please try to resubmit the form
The 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.
Fix it fast
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_protection2Match what you see, then jump to its fix
- 1
Every submit fails, including a fresh page loadThe token id or field name differs between the template and the checkFix - 2
The 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
Fails 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
Only stateless token ids fail, and only on the production host behind a load balancerStateless tokens fail the Origin or Referer check behind a proxyFix
- 1
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:routerConfirmed by symfony.com
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_maxlifetime2Fix
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 = 72003Verify
Wait, then submit again, or submit from the same domain as the page.
php bin/console debug:config framework sessionConfirmed by symfony.com
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/contactConfirmed by symfony.com
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_proxies2Fix
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:clearConfirmed by symfony.com
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
Security
Laravel answers a form or AJAX call with 419 Page Expired
419 Page Expired (a POST, PUT, PATCH or DELETE request)
Laravel could not match the CSRF token in your request to the one stored in the visitor's session.
5 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack 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 fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fix