[wp-hackers] Exemplary code for web single sign-on plugin

Otto otto at ottodestruct.com
Tue Jul 30 23:28:58 UTC 2013

On Tue, Jul 30, 2013 at 4:22 PM, Ryan McCue <lists at rotorised.com> wrote:
> As for the relevant cookie parts, I'm not sure if they're handled by
> Keyring, but they're fairly trivial once you've got a WP_User.

You don't need to handle the cookie parts yourself. Using the
"authenticate" filter correctly will do it for you.

Short version: Hook a filter function to "authenticate". It should
look like this:

add_filter('authenticate', 'example', 40, 3);

function example($user, $username, $password) {
  if ( is_a($user, 'WP_User') ) { return $user; }
  ... do your auth stuff here ...
  return ...something...

- If the function wants to login a user (after whatever verification
process), it should return a valid WP_User object.
- If the function wants to make a user *not* logged in (say the
verification was invalid or failed), it should return a WP_Error
object with a valid error message to display to the user.
- If the function wants to not affect the normal auth process in any
way, it should return the $user value unchanged.

When a valid WP_User is returned, the correct cookies for that user
will be set automatically by the normal process, and the next time
authentication is needed, those cookies will be used (they hook in to
this same filter, but at priority 30). Because of this, you can hook
in at priority 40, and that first is_a line will cause your auth to
not have to happen every time, since the cookie auth will be passing
you a WP_User and you can thus just skip it.


More information about the wp-hackers mailing list