// Generate a token for the form. $token = \Drupal::csrfToken()->get(); // Add the token to the form. $form['my_token'] = [ '#type' => 'hidden', '#value' => $token, ];
// Verify the token on form submission. $token = \Drupal::request()->request->get('my_token'); if (!\Drupal::csrfToken()->validate($token)) { drupal_set_message(t('Invalid security token. Please try again.'), 'error'); return; }This example retrieves the token from the form submission values and verifies it using the `validate()` method of the `csrfToken()` service. If the token is invalid, it displays an error message and prevents further processing. The csrfToken is included in the Drupal core package library.