Diagnosing CodeIgniter CSRF Token Mismatch Errors (403 Forbidden)
Fix CodeIgniter CSRF token mismatches and 403 Forbidden errors with checks for forms, AJAX, cookies, and excluded URIs.
01 Nov 2025, 03:38 UTC

Problem and takeaway
After submitting a form or calling an API endpoint, CodeIgniter returns HTTP 403 Forbidden with a CSRF token mismatch message. The useful takeaway is to match the failure pattern to a single cause—missing token, blocked cookie, regenerated token, or misconfigured exclusion—rather than disabling CSRF protection globally.
Recognizable failure condition
You are likely facing a CSRF issue when all of the following are true:
- The request uses POST, PUT, DELETE, or another state-changing method.
- The response is HTTP 403 Forbidden, often with a message mentioning CSRF or token mismatch.
- The same request works after you refresh the form page and resubmit, or it fails only in specific contexts such as AJAX calls, second browser tabs, or cross-site submissions.
Cause and diagnostic table
| Observed condition | Likely cause | First check |
|---|---|---|
| 403 on ordinary form submission | Hidden CSRF input missing, or browser cookie blocked | View page source; open DevTools > Application > Cookies |
| 403 on AJAX POST/PUT/DELETE | Token not included in request header or body | Inspect Network tab request headers and payload |
| 403 only after opening a second tab or using Back | Token regenerated on every request, invalidating older tokens | Check CSRF regeneration setting in config |
| 403 on API or webhook route | Endpoint not excluded, or excluded incorrectly | Review excluded URI list in config |
| 403 on cross-site POST from another domain | SameSite cookie attribute prevents cookie transmission | Check cookie SameSite and Secure attributes |
Ordered checks
- Confirm the CodeIgniter version and config location. CodeIgniter 3 stores CSRF settings in
application/config/config.php. CodeIgniter 4 stores them inapp/Config/App.php. Property names differ between versions; verify the installed version before editing. - Reproduce the error and inspect the response. Trigger the failing request, then check the response body and framework logs for an explicit CSRF mismatch message. This distinguishes CSRF failures from authentication or authorization errors.
- Check whether the token reaches the server. For HTML forms, view the page source and confirm a hidden input with the configured token name exists. For AJAX requests, open DevTools > Network, reproduce the request, and confirm the required header or body field is present.
- Inspect cookies. In DevTools > Application > Cookies, confirm the CSRF cookie is set for the correct domain and path, and that it is not blocked by browser privacy settings.
- Review regeneration and exclusions. Check whether tokens regenerate on every request and whether the failing URI appears in the exclusion list.
- Test in isolation. Open an incognito window, use a single tab, and resubmit. If the error disappears, the cause is likely token regeneration or cookie state across tabs.
Fixes tied to findings
Missing token in HTML forms
Use the framework's form helper, which injects the CSRF input automatically. Avoid hand-writing <form> tags for state-changing actions unless you add the token manually.
<?= form_open('controller/action') ?>
<!-- CSRF input inserted automatically -->
<?= form_close() ?>
If you must build the form manually, include a hidden field matching the configured token name and value.
Missing token in AJAX requests
Add the CSRF token to each state-changing request. The exact delivery method depends on the CodeIgniter version: some versions accept the token as a POST field with the configured token name, while others read a request header whose name is configurable.
fetch('/api/resource', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('input[name="csrf_test_name"]').value
},
body: JSON.stringify({ name: 'example' })
});
Replace csrf_test_name and X-CSRF-TOKEN with the values configured in your application. Confirm the header name in your version's documentation before deploying.
Token regeneration breaking tabs or Back button
If regeneration on every request is enabled, set it to regenerate only on CSRF failure or once per session, depending on your version's options. Test the back button and parallel tabs after changing this setting.
Excluding trusted endpoints
For API or webhook endpoints that do not modify application state or that use separate authentication, add the URI to the CSRF exclusion list. Limit exclusions to trusted paths; do not exclude state-changing user actions.
// CodeIgniter 3 example; verify property names for your version
$config['csrf_exclude_uris'] = ['api/webhook', 'api/public/status'];
// CodeIgniter 4 example; verify property names for your version
public $CSRFExcludeURIs = ['api/webhook', 'api/public/status'];
Cookie domain, path, and SameSite
If the CSRF cookie is set for a different domain or path than the request, the browser will not send it. For cross-site contexts, SameSite=Lax or SameSite=Strict may block the cookie. Changing to SameSite=None usually requires Secure=true and should be treated as a security decision, not a default fix.
Configuration inspection commands
Run these from the project root as a normal user with read access to the config directory. They are read-only searches.
# CodeIgniter 3
grep -RE "csrf_protection|csrf_token_name|csrf_regenerate|csrf_exclude_uris" application/config/
# CodeIgniter 4
grep -RE "CSRFProtection|CSRFTokenName|CSRFRegenerate|CSRFExcludeURIs" app/Config/
Expected check: output should show the current values, such as csrf_protection = TRUE or an exclusion list containing the failing URI. If no output appears, CSRF may be disabled or configured in an unexpected file.
Risk: none for these read-only commands. Do not run recursive writes in application/config or app/Config without a backup.
State-changing edit and rollback
Editing config files changes application state. Before editing, create a backup:
cp application/config/config.php application/config/config.php.bak
# or
cp app/Config/App.php app/Config/App.php.bak
If the fix introduces new 403 errors, broken sessions, or login failures, restore the backup and retry with a narrower change.
Escalation criteria
Escalate beyond configuration changes when:
- Logs show a CSRF mismatch even though the token and cookie are present and accepted.
- Excluding the URI does not resolve the error, suggesting a web application firewall, reverse proxy, or server module is stripping headers or blocking POST bodies.
- The cookie domain or path differs across subdomains and the token is never transmitted.
- You reproduce the issue on a clean CodeIgniter install with default CSRF settings.
In those cases, capture the request and response headers, the configured CSRF values, and the framework version before contacting support or opening a framework issue.
Limitations and verification
This guide covers built-in CodeIgniter CSRF protection. It does not cover custom CSRF libraries, third-party authentication packages, or framework versions older than the currently supported releases. Behavior differs between CodeIgniter 3 and CodeIgniter 4; verify config class and property names for your installed version.
Practical verification: after applying a fix, reproduce the original failing request in a browser or API client. Expect a successful response instead of HTTP 403, and confirm the framework log no longer records CSRF token mismatches. Test form submission, AJAX submission, the browser Back button, and a second tab before considering the issue resolved.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.