WordPress custom authentication implementation

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 🙂

Leave a Comment