Add optional automatic CSRF protection for AJAX handlers on the frontend
Nobody has claimed this yet.
- Dominant language
- PHP
- Stars
- 1.5k
- Forks
- 246
- Avg merge
- 19h 2m
- Merged PRs (30d)
- 7
Description
Winter CMS Build
dev-develop
PHP Version
7.4
Database engine
MySQL/MariaDB
Plugins installed
No response
Issue description
Frontend AJAX handlers currently do not have CSRF protection enabled.
As per discussion with @LukeTowers, this could be rectified by hooking into the cms.ajax.beforeRunHandler event and checking the token with the verifyCsrfToken() controller method. Care should be taken to prioritize your event listener so that it runs first.
@LukeTowers mentioned he is open to the idea of implementing this in Winter. Could this be an opt-in feature (configurable via enableAjaxCsrfProtection or something along those lines)?
This issue is also documented here:
https://github.com/octobercms/october/issues/696
https://github.com/octobercms/october/issues/3599
Also relevant:
https://github.com/wintercms/winter/commit/260e1f503fe18588f099de5efc928cfe941eed77
https://github.com/wintercms/winter/commit/8da798a5cd2f5f640719550eebebc03e9a9d29d1
Steps to replicate
The server accepts an AJAX request even if it contains an invalid CSRF token.
Workaround
As a temporary workaround, one could register a cms.ajax.beforeRunHandler listener in a custom plugin:
public function boot()
{
Event::listen('cms.ajax.beforeRunHandler', function($controller, $handler) {
/**
* The verifyCsrfToken() method is currently
* protected - use reflection as a temporary
* workaround
*/
$controllerClass = new \ReflectionClass($controller);
$method = $controllerClass->getMethod('verifyCsrfToken');
$method->setAccessible(true);
if( ! $method->invoke($controller)) {
return Response::make(Lang::get('system::lang.page.invalid_token.label'), 403);
}
}, PHP_INT_MAX);
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the cms.ajax.beforeRunHandler event and the controller's verifyCsrfToken() method, then review the linked issue discussions and referenced commits for existing behavior. Done means an opt-in setting protects frontend AJAX handlers from invalid CSRF tokens while leaving protection disabled when the option is not enabled.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- frontend, security
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100