# CSRF error in Ajax POST request

**URL:** <https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626>\
**Category:** Need Help\
**Created:** [November 17, 2020, 11:56am UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626 "2020-11-17T11:56:07Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![joaomario3224](https://avatars.discourse-cdn.com/v4/letter/j/85f322/32.png) [@joaomario3224](https://discourse.cakephp.org/u/joaomario3224)\
**Post date:** [November 17, 2020, 11:56am UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/1 "2020-11-17T11:56:07Z")

</div>

I’m trying to request a Ajax POST, and I’m getting the error 403 (Forbidden) and the error Missing CSRF token body📋  
It’s running on the IIS server, and it’s the 4.0 Cake  
This is the ajax call, the Headers line I found in another forum, but successless

```
$.ajax({
	url: url,
	type: 'POST',
	contentType: false,
	processData: false,
	headers: {
		'X-CSRF-Token': "<?= $this->request->getParam('_csrfToken'); ?>"
	 },
	data: function(){
		var data = new FormData();
		idanexo = '#Anexos'+tarefa;
		jQuery.each(jQuery(idanexo)[0].files, function(i, file) {
			 data.append('file-'+i, file);
		});
		data.append( 'Comentario', comentario ); 
		data.append( 'NumTarefa', tarefa ); 
		return data;
	}(),
	success: function(result) {
		viewTarefa(tarefa);
	},
});

```

In the Application.php, there’s this function:

```
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
    $csrf = new CsrfProtectionMiddleware();

    $middlewareQueue
        // Catch any exceptions in the lower layers,
        // and make an error page/response
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))

        // Handle plugin/theme assets like CakePHP normally does.
        ->add(new AssetMiddleware([
            'cacheTime' => Configure::read('Asset.cacheTime'),
        ]))

        ->add(new RoutingMiddleware($this));

    // Ensure routing middleware is added to the queue before CSRF protection middleware.
	$middlewareQueue->add($csrf);
	
    return $middlewareQueue;
}
```

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [November 17, 2020, 7:18pm UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/2 "2020-11-17T19:18:32Z")

</div>

You should append the token as a field in the `POST` data iirc.

```auto
data: function(){
  var data = new FormData();
  idanexo = '#Anexos'+tarefa;
  jQuery.each(jQuery(idanexo)[0].files, function(i, file) {
    data.append('file-'+i, file);
  });
  data.append( 'Comentario', comentario ); 
  data.append( 'NumTarefa', tarefa );

  // Add CSRF
  data.append(`_csrfToken`, `<?= $this->request->getParam('_csrfToken'); ?>`);

  return data;
}()

```

---

<div class="post-metadata">

**Author:** ![joaomario3224](https://avatars.discourse-cdn.com/v4/letter/j/85f322/32.png) [@joaomario3224](https://discourse.cakephp.org/u/joaomario3224)\
**Post date:** [November 17, 2020, 7:30pm UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/3 "2020-11-17T19:30:13Z")

</div>

I’m still getting the same error  
When I debug the $this-\>request-\>getParam(’\_csrfToken’) I always get null, I don’t think it should happen

---

<div class="post-metadata">

**Author:** ![Jawfin](https://avatars.discourse-cdn.com/v4/letter/j/dbc845/32.png) [@Jawfin](https://discourse.cakephp.org/u/Jawfin)\
**Post date:** [November 17, 2020, 8:49pm UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/4 "2020-11-17T20:49:56Z")

</div>

This doesn’t answer your question directly, but instead it shows a working solution of using AJAX with CakePHP 4 and CSRF and as a bonus the form tampering protection too: -

> [@Working CSRF AJAX in CakePHP 4 - looking for criticism!](https://discourse.cakephp.org/t/working-csrf-ajax-in-cakephp-4-looking-for-criticism/7714/5):
>
> This is a complete build of a running AJAX using CakePHP4 with CSRF and Form Tampering protection. It reverses a user entered string. Create the ajax project: - composer self-update && composer create-project --prefer-dist cakephp/app:4.\* ajax Edit config/app\_local.php ... 'username' =\> 'root', 'password' =\> 'secret', 'database' =\> 'cake\_ajax', ... Or whatever your database is. For this demonstration I am using this table: - DROP TABLE IF EXISTS `myajax`; CREATE TABLE `myajax` ( …

In there it doesn’t access the token directly from `getParam()`, but uses the CakePHP form creator to populate the hidden field it uses for passing the token (so its in the form, not the header). It may help.

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [November 17, 2020, 11:51pm UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/5 "2020-11-17T23:51:02Z")

</div>

I just realized a minor error of mine…  
You should use `$this->request->getAttribute('csrfToken')` instead of `$this->request->getParam('_csrfToken')`.  
Sending it as a header is still fine this way.

---

<div class="post-metadata">

**Author:** ![joaomario3224](https://avatars.discourse-cdn.com/v4/letter/j/85f322/32.png) [@joaomario3224](https://discourse.cakephp.org/u/joaomario3224)\
**Post date:** [November 18, 2020, 11:21am UTC](https://discourse.cakephp.org/t/csrf-error-in-ajax-post-request/8626/6 "2020-11-18T11:21:12Z")

</div>

Thank you, this worked
