Leave a Reply

4 comments

  1. OK, the approach that’s working for me is as follows:

    1. Assume that the main site user database is authoritative. The main site login cookie contains an ID and a hash of the site password.

    2. Get the cookie from the main site and revalidate it against the main site’s authentication API

    3. If valid, use the email address from the return value as the 'user_login' value for WP, and the hashed site password as the WP password.

    4. Test if this user exists in WP by using wp_authenticate('user_login', 'user_pass'). This returns a WP_User object on success, or a WP_Error object on failure.

    5. If WP_Error/is_wp_error(), then use use wp_update_user() to create a user (or update a user with a changed password).

    6. Login via wp_set_current_user(), wp_set_auth_cookie() and do_action('wp_login, id)

    (This is all contained in a function that’s attached to the 'init' action)

    This seems to be working – valid site users unknown to WP are automatically created. Password changes are catered for, and if the site cookie is set, and the WP user exists, the SSO is automatic and pretty seamless.

  2. Enabling Single-Sign-On in WordPress took me 18+ hours of struggle but might take you only a few minutes:

    Basically, you’ll want to use https://wordpress.org/plugins/wp-force-login/ and a modified version of https://as.wordpress.org/plugins/jwt-authenticator/ and then create an auth-protected endpoint on your main site that generates a JWT (JSON Web Token) and redirects back to the special URL of your WordPress site.

    See full code here.