TL;DR: Here’s how you can programmatically authenticate a user into WordPress as long as you have a verified user ID for said user.
Earlier this week, I shared how to import necessary core files to programmatically manage users in the administration area of WordPress. Along those same lines, if you’re working with a third-party service for login and authentication, it may be useful to know how to programmatically redirect to the administration area once you have a valid user ID.
Programmatically Authenticate a User
Assume, for a moment, that you’re working with a service that will use the user’s email address as it’s stored in WordPress as a form of authentication.
This means that the user’s email address allows them to use providers such as Google, OAuth, or some other system, maybe JWT even, to provide single-sign on functionality.
Regardless of the provider, assume that the flow works something like this:
- You click a link and are taken to a third-party authentication form
- You provide your email address and password,
- The provider uses this information to authenticate you,
- Assuming your password for said service is valid, the user is redirected back to WordPress
- You attempt to find the user by their email in WordPress,
- You are then logged into the WordPress administration area
To make this code general enough, or rather not specific to any one service, assume once you have been redirected back to WordPress, you need make sure the user exists by the provided email:
$user = get_user_by('email', $providerEmail);
From here, you can then use the standard WordPress cookie authentication process to log the user into WordPress:
// TODO: If the user doesn't exist, create them or generate an error message and exit. // If the user exists, then set an auth cookie. wp_clear_auth_cookie(); wp_set_current_user($user->data->ID); wp_set_auth_cookie($user->data->ID); // Now redirect to the administration area. wp_safe_redirect(admin_url(), 302, 'Third-Party SDK'); exit;
Obviously this is high-level but it should be enough to demonstrate the point for now.
In a future article, I plan to talk much more about this in-depth but if you’re in the process of working on something like this at the moment (or may be in the future), this is something that’s useful to know.