POST via Ajax returns 403 with CSRF enabled |
Hello Community,
I've deployed the latest Codeigniter 4.0.2 version and I have an issue when submitting a form with Post method via Ajax when CSRF is enabled, I've tried my best to figure out what is wrong but still no luck. Notice that: - When CSRF is disabled, the Ajax call is successful - If I don't use Ajax and I enable CSRF, the controller handles correctly the request with 200 code Allow me to share with you the details: - CSRF enabled globally in the file App\Config\Filters.php: Code: // Always applied before every request - CSRF configuration: Code: public $CSRFTokenName = 'csrf_token'; - A simple contact form with the CSRF hidden input created manually: Code: <form name='contactForm' class="contactForm" id='contactForm'> - When submitting the form, the following Javascript code is being executed: Code: const apiUrl = '/api/contact'; - When accessing URL /api/contact, the following Controller handles the request: Code: <?php namespace App\Controllers; - Analyzing the Payload, it is correct: Code: csrf_token=563def7f2e22a4df1f6e53ce8f0b75d7&msg_name=jdoe It matches with the cookie: Code: Cookie: csrf_cookie=563def7f2e22a4df1f6e53ce8f0b75d7 Mind that I've tried another way to pass the CSRF token, directly to the headers: Code: $.ajaxSetup({ It is added correctly: Code: csrf_token: 563def7f2e22a4df1f6e53ce8f0b75d7 - In all my attempts, the same result, 403 error code: Code: code: 403 What am I missing here? CSRF token name and CSRF hash are passed correctly to the controller but it keeps showing 403 error only when the request is performed via Ajax. Could you please shed some light on this issue? Thank you in advance for taking your time reading this. |
Messages In This Thread |
POST via Ajax returns 403 with CSRF enabled - by marcvidalim - 04-05-2020, 11:39 AM
RE: POST via Ajax returns 403 with CSRF enabled - by Gary - 04-06-2020, 08:27 AM
RE: POST via Ajax returns 403 with CSRF enabled - by marcvidalim - 04-06-2020, 09:30 AM
RE: POST via Ajax returns 403 with CSRF enabled - by Gary - 04-06-2020, 12:08 PM
RE: POST via Ajax returns 403 with CSRF enabled - by marcvidalim - 04-06-2020, 12:36 PM
RE: POST via Ajax returns 403 with CSRF enabled - by Gary - 04-06-2020, 03:16 PM
RE: POST via Ajax returns 403 with CSRF enabled - by marcvidalim - 04-08-2020, 02:23 AM
|