# Cakephp 3.8 CSRF token mismatch

**URL:** <https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469>\
**Category:** Need Help\
**Tags:** release\
**Created:** [March 14, 2020, 7:15pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469 "2020-03-14T19:15:41Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 14, 2020, 7:15pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/1 "2020-03-14T19:15:41Z")

</div>

Hi,

I have controllers that keep throwing CSRF token mismatch. on form submit…  
But i checked, the token is there and correct in the form, strangely all my controllers with prefix are working properly, those without are not can be a path to solution?

Thanks  
Kind regards

at those lines i have debugged

```
    $cookies = $request->getCookieParams();
    $cookie = Hash::get($cookies, $this->_config['cookieName']);
    $post = Hash::get($request->getParsedBody(), $this->_config['field']);
    $header = $request->getHeaderLine('X-CSRF-Token');

    debug($cookie);
    debug($post);
    debug($header);

```

and here are the outputs

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **227** )  
‘15fd588e03433b36c7d985cda310df52529818f9ccd9b0fa6fb83cc6b049b48fc538ecad67dc93fb8cbdb9c3cf7f21a900ea93cdbe5fb5af996097397aee5ef3’

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **228** )  
‘15fd588e03433b36c7d985cda310df52529818f9ccd9b0fa6fb83cc6b049b48fc538ecad67dc93fb8cbdb9c3cf7f21a900ea93cdbe5fb5af996097397aee5ef3’

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **229** )  
‘’

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **227** )  
null

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **228** )  
‘15fd588e03433b36c7d985cda310df52529818f9ccd9b0fa6fb83cc6b049b48fc538ecad67dc93fb8cbdb9c3cf7f21a900ea93cdbe5fb5af996097397aee5ef3’

**\src\Http\Middleware\CsrfProtectionMiddleware.php** (line **229** )  
‘’

So first time the header was missing the token on a regular form (not ajax)  
ANd second time the cookie in the params is nulll…

## ALSO what i don’t get is why on a single form submission it goes twice through the validation

## UPDATE:

Defintely it comes from the fact that this validation is being called twice instead of once, as long as I comment this line  
//unset($body[$this-\>\_config[‘field’]]);  
Then of course it does not throw the same token mismatch because at teh second check the field is still there but why IT IS CHECKING twice??

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 14, 2020, 8:18pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/2 "2020-03-14T20:18:31Z")

</div>

You haven’t shown where that `unset` line is, or anything about where the data is validated, so it’s quite hard to tell why it might be checking twice.

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 14, 2020, 8:34pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/3 "2020-03-14T20:34:05Z")

</div>

the unset is happening here  
protected function \_validateAndUnsetTokenField(ServerRequest $request)  
{  
if (in\_array($request-\>getMethod(), [‘PUT’, ‘POST’, ‘DELETE’, ‘PATCH’], true) || $request-\>getData()) {  
$this-\>\_validateToken($request);  
$body = $request-\>getParsedBody();  
if (is\_array($body)) {  
// unset($body[$this-\>\_config[‘field’]]);  
$request = $request-\>withParsedBody($body);  
// debug($body);  
}  
}  
return $request;  
}  
ANd i think from teh code those function are being call on any PUT, GET, POST,…or i there is getData…  
so it means that there in those controllers the \_validateAndUnsetTokenField is being called twice…

Thanks for taking of your time (AGAIN lol) to check this…

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 14, 2020, 10:43pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/4 "2020-03-14T22:43:50Z")

</div>

You could dump the stack trace in this function to find why it’s getting called twice. I’m going to guess that you’ve simply added this middleware to your stack twice, presumably the second one is in code that the “controllers with prefix” aren’t running, hence why they’re fine.

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 14, 2020, 11:03pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/5 "2020-03-14T23:03:21Z")

</div>

I feel dumb, last time you told me already about stack trace, could not get it to run on my project ☹

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 12:43am UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/6 "2020-03-15T00:43:12Z")

</div>

[https://www.php.net/manual/en/function.debug-print-backtrace.php](https://www.php.net/manual/en/function.debug-print-backtrace.php)

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 15, 2020, 2:41pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/7 "2020-03-15T14:41:48Z")

</div>

Hi,  
now i feel more dumb, i am pretty good on googling and dr google teachnig but this one I had not find…  
“\_validateAndUnsetTokenField” is indeed being called twice now how o understand when and how?  
Now more dumb, can’t attache the file, the print is 241 pages ☹

> **[cakephp - error - \_validateAndUnsetTokenField.docx](https://drive.google.com/file/d/19N_3VmXhhL-AGVOjCs4N1t0MMxEbANzt/view?usp=sharing)**
>
> Google Drive file.

Thanks  
Regards

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 3:32pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/8 "2020-03-15T15:32:03Z")

</div>

Use the `DEBUG_BACKTRACE_IGNORE_ARGS` argument, and that’ll get WAY shorter.

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 15, 2020, 3:36pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/9 "2020-03-15T15:36:11Z")

</div>

> **[cakephp - error - \_validateAndUnsetTokenField.docx](https://drive.google.com/file/d/1jAvCFu1TEafThLzgroXVr3H-0bUCEwA_/view?usp=sharing)**
>
> Google Drive file.

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 4:27pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/10 "2020-03-15T16:27:15Z")

</div>

Yeah, the only explanation for that stack trace is that you’ve got the CSRF middleware added twice.

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 15, 2020, 5:04pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/11 "2020-03-15T17:04:46Z")

</div>

Yes indeed I am trying to figure how and why, thought maybe creating multiplke entities and son, but no way, all this stuff happens on the post/put, i have no control on this …  
I thought maybe the isAuthorized frrom the app controller on this event 🙂 if (!$this-\>request-\>getParam(‘prefix’)) {  
return true;  
}  
beucase this is not happening when i am on prefixed routes…

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 5:26pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/12 "2020-03-15T17:26:21Z")

</div>

You very much have control over when and where the middleware is added. Look through your code for CsrfProtectionMiddleware, that should find where you’re adding it. If it’s not immediately obvious from those results why it’s being added twice, then dump the stack trace there to find where those calls are coming from.

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 5:28pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/13 "2020-03-15T17:28:20Z")

</div>

P.S. What you included before looks like the output of `debug_backtrace`, not `debug_print_backtrace `. The former is machine-friendly output, the latter is much more human-friendly.

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 15, 2020, 10:02pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/14 "2020-03-15T22:02:26Z")

</div>

The middleware is added once in the routing:

$routes-\>registerMiddleware(‘csrf’, new CsrfProtectionMiddleware([  
‘httpOnly’ =\> true,  
]));  
/\*  
\* Apply a middleware to the current route scope.  
\* Requires middleware to be registered through `Application::routes()` with `registerMiddleware()`  
\*/  
$routes-\>applyMiddleware(‘csrf’);  
This the default setup,i don’t add it anymore as a component as deprecated…

> **[cakephp - error - \_validateAndUnsetTokenField.docx](https://drive.google.com/file/d/1QJgUe6_p13EZgueNV-qs6sXZoxZjB8uM/view?usp=sharing)**
>
> Google Drive file.

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 15, 2020, 10:27pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/15 "2020-03-15T22:27:24Z")

</div>

From that stack trace, it’s going through middleware in the following order:

- CSRF
- Error handler
- Asset
- Routing
- CSRF again

So yeah, it’s being loaded twice. Take a look at where those other ones are added for hints. Dump the stack trace at the point where this routing setup is being handled, to see if it’s being called twice (and if so, from where).

---

<div class="post-metadata">

**Author:** ![lpg](https://avatars.discourse-cdn.com/v4/letter/l/e47774/32.png) [@lpg](https://discourse.cakephp.org/u/lpg)\
**Post date:** [March 19, 2020, 8:46pm UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/16 "2020-03-19T20:46:17Z")

</div>

Hi,

ok found out something, it comes from the routing ,  
it has  
$routes-\>registerMiddleware(‘csrf’, new CsrfProtectionMiddleware([  
‘httpOnly’ =\> true,  
]));  
$routes-\>applyMiddleware(‘csrf’); if i comment this line with the routes without prefix, it goes just once through the process BUT i realized that with routes WITH prefix, it does not process the middleware at all!!!  
SO i think i misconfigured something in my routes which I am attaching,it definitely comes from there…

> **[routes.php](https://drive.google.com/file/d/1yqkGlH7LpwZSTFppPs6uU6ZFg3hpgNQy/view?usp=sharing)**
>
> Google Drive file.

  
Thanks

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 20, 2020, 4:10am UTC](https://discourse.cakephp.org/t/cakephp-3-8-csrf-token-mismatch/7469/17 "2020-03-20T04:10:30Z")

</div>

I am very much a novice at routing, so I’ll let someone else comment on this, if you can’t sort it out yourself from the documentation. At least you know where it’s coming from now.
