Form protection tool

The TYPO3 Core provides a generic way of protecting forms against cross-site request forgery (CSRF).

Usage in the backend

For each form in the BE (or link that changes some data), create a token and insert it as a hidden form element. The name of the form element does not matter; you only need it to get the form token for verifying it.

// use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;

$formToken = FormProtectionFactory::get()
    ->generateToken('BE user setup', 'edit');
$this->content .= '<input type="hidden" name="formToken" value="' . $formToken . '">';
Copied!

The three parameters $formName, $action (optional) and $formInstanceName (optional) can be arbitrary strings, but they should make the form token as specific as possible. For different forms (for example, BE user setup and editing a tt_content record) or different records (with different UIDs) from the same table, those values should be different.

For editing a tt_content record, the call could look like this:

// use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;

$formToken = FormProtectionFactory::get()
    ->generateToken('tt_content', 'edit', $uid);
Copied!

Finally, you need to persist the tokens. This makes sure that generated tokens get saved, and also that removed tokens stay removed:

// use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;

FormProtectionFactory::get()
    ->persistTokens();
Copied!

In backend lists, it might be necessary to generate hundreds of tokens. So, the tokens are not automatically persisted after creation for performance reasons.

When processing the data that has been submitted by the form, you can check that the form token is valid like this:

// use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
// use TYPO3\CMS\Core\Utility\GeneralUtility;

if ($dataHasBeenSubmitted &&
    FormProtectionFactory::get()->validateToken(
        (string) GeneralUtility::_POST('formToken'),
        'BE user setup',
        'edit'
    ) ) {
    // process the data
} else {
    // No need to do anything here, as the backend form protection will
    // create a flash message for an invalid token
}
Copied!

Usage in the frontend

Usage is the same as in backend context:

   // use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
   // use TYPO3\CMS\Core\Utility\GeneralUtility;

   $formToken = FormProtectionFactory::get()
       ->generateToken('news', 'edit', $uid);

if ($dataHasBeenSubmitted
	&& FormProtectionFactory::get()->validateToken(
		GeneralUtility::_POST('formToken'),
		'news',
		'edit',
		$uid
	)
) {
	// process the data
} else {
	// Create a flash message for the invalid token
       // or just discard this request
}
Copied!