如何向WordPress登录和注册添加自定义身份验证

时间:2020-09-14 作者:chris

我想创建一个函数来停止wordpress中的登录过程,让用户在完全登录之前验证otp表单或代码。我打算在用户的电子邮件和密码之后进行拦截

这就是我试过的

add_filter( \'authenticate\', \'smyles_check_custom_auth\', 10, 3 );

function smyles_check_custom_auth( $user, $username, $password ){
    
    $otp_check = \'bad\';  // variable returned from query but just using bad for testing
    
    if( !$otp_check == \'good\' ){
        
          return confirm_form();
        
    }
    elseif($otp_check == \'good\'){
        
        return $user;
    }
    
    return new WP_Error( __( \'OTP Check failed\' ) );
    
}
然而,它并没有起作用,如果我将优先级设置为20,3,它只会停止表单验证,而不会显示任何错误消息

我的目标是先验证用户名和密码,然后禁用提交按钮和用户名和密码字段,并显示我的确认otp代码,一旦用户确认正确的otp,登录过程将继续,这是一个重定向过程,希望能重定向到管理员。如果我将优先级设置为10,3则无论我有什么代码,都会提交表单并登录用户。

工作流程如下:

如果用户名和密码与Wp\\U users表中的用户匹配,则调用mycustom send otp to the User email()。如果用户名和密码与Wp\\U users表中的用户匹配,则调用mycustom send otp to the User email()所以我的问题是要知道一个钩子,我可以在我的otp确认表单()中钩子它,这样它在用户名和密码身份验证之后,但在调用wpsignon()操作之前执行。只是中间拦截。

1 个回复
SO网友:sMyles

是的,有一个authenticate 您可以在wp_authenticate 函数,并返回WP_Error 如果登录失败。

/**
 * Filters whether a set of user login credentials are valid.
 *
 * A WP_User object is returned if the credentials authenticate a user.
 * WP_Error or null otherwise.
 *
 * @since 2.8.0
 * @since 4.5.0 `$username` now accepts an email address.
 *
 * @param null|WP_User|WP_Error $user     WP_User if the user is authenticated.
 *                                        WP_Error or null otherwise.
 * @param string                $username Username or email address.
 * @param string                $password User password
 */
$user = apply_filters( \'authenticate\', null, $username, $password );
这正是WordPress内部验证用户名和密码的方式,这些是使用的默认过滤器:

add_filter( \'authenticate\', \'wp_authenticate_username_password\', 20, 3 );
add_filter( \'authenticate\', \'wp_authenticate_email_password\', 20, 3 );
add_filter( \'authenticate\', \'wp_authenticate_spam_check\', 99 );
我建议您将过滤器的优先级设置为10,或小于20(这是在检查用户名/密码时),以便首先运行检查。

如果测试通过,只需返回通过的第一个变量,例如:

add_filter( \'authenticate\', \'smyles_check_custom_auth\', 10, 3 );

function smyles_check_custom_auth( $user, $username, $password ){
    
    $otp_check = false;
    
    if( $otp_check ){
        return $user;
    }
    
    return new WP_Error( __( \'OTP Check failed\' ) );
}