In a module I am writing, I need to add a hidden field in the registration form, similarly to what the Honeypot module does.
$form['honeypot_time'] = [ '#type' => 'hidden', '#title' => t('Timestamp'), '#default_value' => mymodule_get_signed_timestamp(time()), '#element_validate' => ['mymodule_signed_timestamp_validate'], '#cache' => [ 'max-age' => 0, ], ];
mymodule_get_signed_timestamp() concatenates the timestamp with a value used to avoid the timestamp is arbitrary changed. It could be computed in one of two ways:
- Using the csrf_token service, which by default provides
The choose is then between one of the following snippets.
use \Drupal\Component\Utility; $token = Crypt::hmacBase64($value, \Drupal::service('private_key')->get());
use \Drupal\Core\Access; $token = \Drupal::csrfToken()->get($value);
The difference is apparently just that the csrf_token service's methods use, as part of the key passed to
Crypt::hmacBase64(), also the session's data and the hash salt set in the settings.php file.
Considering that, in most of the cases, I would be altering a form submitted from anonymous users who tries to register an account (but I cannot exclude I could be adding that form element to forms submitted from registered users), should I use the first method or the second one?