Support » Plugins » Can WordPress's nonces be used across different users?

  • I am writing a plugin that needs to send a notification email with a link (URL) when one user takes an action to the inbox of a second user. I’m aware of how WP’s nonces can (and should) be used to protect front-end form submission from CSRF attacks and already use them throughout my plugin.

    My question is: can this same WP nonce mechanism be used across the requests of two different users?

    Specifically, I’ve noticed that when I use wp_nonce_url() as part of a function while a given user (User A) is set to the “current user,” the nonce is considered “invalid” when a second user (User B) attempts to access the page at the URL generated by wp_nonce_url(). Is this by design, or is there some way to use nonces across user accounts?

    A simplified excerpt of my code:

                // Send an email notification with a confirmation link to the second user
                $user_1 = get_userdata($user_1_id);
                $subject = sprintf(__('%s wants you to join their team', 'my-plugin'), $current_wp_user->display_name);
                $old_wp_user = wp_get_current_user();
                wp_set_current_user($user_1->ID);
                $msg = wp_nonce_url(
                    admin_url(
                        'index.php?page=' . $this->prefix . 'confirm-join'
                    ),
                    $this->prefix . 'confirm-join', $this->prefix . 'nonce'
                );
                wp_set_current_user($old_wp_user->ID);
                wp_mail($user_1->user_email, $subject, $msg);
    

    In this snippet, I attempted to make $user_1 (the recipient of the notification) the “current” WP user with wp_set_current_user() and then created a nonce with wp_nonce_url(). However, I can’t get this nonce to verify (using wp_verify_nonce() always returns false) when accessed by $user_1 when they click on the link in the email message.

    Do I misunderstand how nonces should work across different users or is there a problem with my code? Thank you for your help.

  • The topic ‘Can WordPress's nonces be used across different users?’ is closed to new replies.