我正在为使用插件JWT Auth登录到我的站点的用户生成一个JWT令牌,该令牌将用于外部仪表板。
我面临的问题是,要生成JWT令牌,您需要将username
和password
作为form-data
传递到/wp-json/jwt-auth/v1/token
端点,但是存储在数据库中的密码是散列的,不能解密,那么这有什么解决方案呢?我无法向端点发送纯文本密码。
期待您的建议。
发布于 2021-02-27 12:39:25
对于面临类似问题的开发人员,这里是我为达到预期结果所做的工作。
最好的方法是从头开始开发功能,但由于时间紧迫,我选择修改JWT Auth插件。
我在文件get_token
中修改了class-auth.php
方法。我所做的是,最初的方法是查找params、username
和password
,我对其进行了修改,以便根据需要接收userID
。为什么是userID
?这是因为我正在运行一个cURL
调用,以便在用户登录后获取用户数据。下面是get_token
方法的代码,如果有人想要使用它。虽然这是一个小的修改,但它产生了所需的结果。谢谢大家的建议。快乐编码
public function get_token(WP_REST_Request $request)
{
$secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false;
$userID = $request->get_param('user_id');
$custom_auth = $request->get_param('custom_auth');
// First thing, check the secret key if not exist return a error.
if (!$secret_key) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 403,
'code' => 'jwt_auth_bad_config',
'message' => __('JWT is not configurated properly.', 'jwt-auth'),
'data' => array(),
)
);
}
// Getting data for the logged in user.
$user = get_user_by('id', $userID);
// If the authentication is failed return error response.
if (!$user) {
// $error_code = $user->get_error_code();
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 403,
'code' => 404,
'message' => 'User does not exists.',
'data' => array(),
)
);
}
return $this->generate_token($user, false);
}
发布于 2021-06-07 20:37:41
您可以使用custom_auth参数来处理这种情况。
编辑
JWT有一个名为jwt_auth_custom_auth的过滤器,当它接收到包含'custom_auth‘的有效负载时,它将运行,您需要使用add_fitler函数连接到该过滤器,参见下面的代码。
在我的例子中,第一个代码块转到我的rest自定义端点,在那里我只使用电子邮件地址来登录/注册用户。
第二个块是挂接过滤器,我选择将它放在插件文件中,但您也可以将它放在主题的function.php文件中
您可以在这个文件中看到这个逻辑:\plugins\jwt\class-auth.php第115行-> 160。
$_request = new WP_REST_Request( 'POST', '/jwt-auth/v1/token' );
$_request->set_header( 'content-type', 'application/json' );
$_request->set_body(
json_encode(
[
'username' => $email,
'custom_auth' => true,
]
)
);
$response = rest_do_request( $_request );
return $response->data['data']['token']; // this will return a token
在你的function.php里
add_filter(
'jwt_auth_do_custom_auth',
function ( $custom_auth_error, $username, $password, $custom_auth ) {
if ( is_wp_error( $custom_auth_error ) ) {
return null;
}
$user = get_user_by( 'email', $username );
return $user;
},10,4);
我希望这能帮到你
注:未测试
https://wordpress.stackexchange.com/questions/384131
复制相似问题