I have a wordpress site (lets call it site1) and another site with oauth2 (site2).
When a new user is created, a record is created in both site1 and site2 databases with the same email as username, the typed password hashed in site2 database and a dummy (e.g. “pass”) password for site1 database. Then login action authenticates with site2 database using a RESTfull API. If authentication is successful, I want to programmatically log the user in to site1 (wordpress), if not, an error object should be injected to site1.
My question is which wordpress filter is more suitable for this, wp_authenticate_user or wp_authenticate and where should wp_signon fit in?
1 Answer
I’m currently working on a plugin to do this on a large scale, since I have multiple sites that I want to sync; but I don’t mind sharing the info with you.
I understood [from what you said] that the user’s credentials have already been verified on site2 – so there’s no need to use any of those functions to verify them again. All you need to do now is create the session on your WordPress site.
This means then that the function you are looking for is wp_set_auth_cookie. It would create the user session without requiring credentials. The function takes the user ID as the first argument, which is most important, and you would fire this before WordPress initiates (like at the top of your functions.php file).
If you want to do this via a web service, I would advise that you use a 2-stage process, for security reasons. First, you could push the user ID to a table storing “authenticated sessions”, identifying the user with a unique session ID (some form of hash, of IP, user-agent, etc). In the 2nd stage, you could fire that function as soon as that same person visits the WP website.
The other option is to create a session code on site2, then send the user to site 1 with that code in their hand (query_string, or form post). When they get to site1, a call back to site2 would be used to verify it, and then use the function above to simply create the session.