I created a plugin to allow my website to have its own login functionality.
My project has a new requirement which is to log in to the user with my own authentication method and not the one provided by WP.
Which actions and filters do I need to use so I can create my own authentication method? And once my authentication method is successful how can I log in the user to the WP site? I don’t want to use a plugin.
Would someone shed some light or point me to a guide that shows me how to achieve it.
Currently I only know that my own authentication method should be implemented in:
add_action('wp_authenticate_user', 'custom_authentication', 10, 2);
1 Answer
This question Set up WP Authentication from External API has a link to a blog. That put me in the right direction and shed some light on my work (Thanks @Rup).
class CustomLogin
{
/**
* Initializes the plugin.
*
* To keep the initialization fast, only add filter and action hooks in the constructor.
*/
public function __construct()
{
add_filter('authenticate', array($this, 'my_custom_authentication'), 10, 3);
remove_action('authenticate', array($this, 'wp_authenticate_username_password'), 20);
remove_action('authenticate', array($this, 'wp_authenticate_email_password'), 20);
add_action('authenticate', array($this, 'new_wp_authenticate_email_password'), 20, 3);
}
public function my_custom_authentication($user, $userName, $password)
{
$authenticationResponse = $this->custom_authentication($userName, $password);
if (isset($authResponse['Auth_Error']) && !empty($authResponse['Auth_Error']))
return 0;
$user = get_user_by('email', $authenticationResponse['Auth_Email']);
if (!empty($user))
return $user;
else
return 0;
// Add WP_Error message where ever is convinient for you
}
public function new_wp_authenticate_email_password($user, $userName, $password)
{
if ($user instanceof WP_User) {
return $user;
}
// Validations and WP_Error message
}
}
I used a plugin and the code above first validates a user on the external service. If the user is found on the external service and then on WordPress I return the user which logs the user in, if not, I return an error message.
The numbers you see in the constructor are priorities which determine the moment that the action or filter will be triggered.
add_filter('authenticate', array($this, 'my_custom_authentication'), 10, 3);
If you want to know more about those priorities numbers please have a read to this: https://usersinsights.com/wordpress-user-login-hooks/
Thanks 🙂