Is Nonce Verification (CSRF) required for WordPress Custom Bulk User Actions?

In WordPress, nonces (number used once) are security tokens that help protect against CSRF (Cross-Site Request Forgery) attacks. Nonce verification is generally recommended for actions that involve user interactions to ensure that the request is legitimate and not forged by a malicious party.

When it comes to custom bulk user actions in WordPress, nonce verification is indeed a good practice to enhance the security of your application. The nonce should be included in the form or request to validate that the action is intended by the user.

Looking at the WordPress core, you’ve correctly noted that nonce verification is performed for various bulk user actions using check_admin_referer('bulk-users'). This helps ensure that the request is legitimate. However, you’ve observed that in some cases, the _wpnonce parameter is removed before reaching the custom bulk actions.

If nonce verification is not performed as part of the custom bulk user actions, it might be a potential security vulnerability. It’s possible that the WordPress Core handles certain cases differently due to historical reasons or specific use cases.

Here’s a basic example of how you can add nonce verification for a custom bulk user action using the handle_bulk_actions-{$screen} filter:

// Hook into the bulk action for users
add_filter('handle_bulk_actions-users', 'custom_bulk_user_action', 10, 3);

function custom_bulk_user_action($redirect_to, $doaction, $user_ids) {
    // Verify nonce
    $nonce = isset($_REQUEST['_wpnonce']) ? $_REQUEST['_wpnonce'] : '';

    if (!wp_verify_nonce($nonce, 'bulk-users')) {
        // Nonce verification failed, handle accordingly (e.g., show an error)
        wp_die('Security check failed!');
    }

    // Perform your custom bulk action logic here

    // Redirect back to the users page after the action is completed
    return add_query_arg('bulk_action_completed', 1, $redirect_to);
}

In this example, the wp_verify_nonce function is used to check the nonce’s validity. If the verification fails, it displays an error message using wp_die. Adjust the code according to your specific use case and error handling requirements.

Please note that the specifics might vary based on the context and WordPress version, so always refer to the latest WordPress documentation and best practices.