My module has 2 small forms which allow visitors to submit certain information.

Problem is when I am not logged in, no CSRF token is being added to the forms - so anonomous users/everyone are bypassing the CSRF. Can't find any documentation on this issue, could anyone point me in the right direction so i can get my CSRF tokens?

It is a requirement of my security testing that all forms include CSRF.


If you look at drupal_prepare_form() it says

since tokens are session-bound and forms displayed to anonymous users are very likely cached, we cannot assign a token for them.

If you do want to go ahead with this, the following works when quickly tested with the default search and comment forms.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (!isset($form['#token'])) {
    $form['#token'] = $form_id;
    $form['form_token'] = array(
      '#id' => drupal_html_id('edit-' . $form_id . '-form-token'), 
      '#type' => 'token', 
      '#default_value' => drupal_get_token($form['#token']),

Be careful about page caching however (and a reverse proxy if you use one) if you do go down this road.

  • Saw that, do you know of any work arounds? – Graeme May 22 '12 at 11:26
  • I've not heard of any I'm afraid. Looking at the code I don't see a problem with just populating $form['#token'] and $form['form_token'] but this isn't tested. Would you be able to update your question to include why you're worried about CSRF on an anonymous account? – Andy May 22 '12 at 11:53
  • I have strict security testing requirements. The forms can't be left open to attack. It's a fairly simple thing to implement, i'm not sure why Drupal is making it so difficult. – Graeme May 22 '12 at 12:19
  • 1
    I think the Drupal way is to use registered users as and when you're opening up functionality that you want to protect from CSRF. I've never needed to have a form that was protected from CSRF and visible to anonymous users (not to say it can't happen, just wondering if it isn't an unusual situation). – Andy May 22 '12 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.