![](/img/trans.png)
[英]Authenticating users in WordPress using wp_set_auth_cookie
[英]wp_set_auth_cookie() not working for some users only
我有一个登录表单,并使用REST api服务登录到Wordpress。 我可以使用表格登录到wordpress。 但是对于某些用户,wp_set_auth_cookie()函数无法正常工作,并且我收到502错误的网关。 谁能帮我解决这个问题?
这是我的登录端点功能
function user_authentication() {
global $wp_rest_auth_cookie;
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = false;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID);
wp_set_auth_cookie ( $user->ID );
$wp_rest_auth_cookie = wp_create_nonce('wp-rest') ;
$token = encrypt_decrypt('encrypt',$user->ID);
$name = get_name($user->ID);
$response = array(
'status'=> 'success',
'token' => $token,
'username' => $name,
'uname' => $user->ID
);
return json_encode( $response);
}else{
$response = array(
'status' => 'fail',
'message'=> "The username and password you entered don't match."
);
return json_encode($response);
}
die();
}
将以下代码添加到您的代码中,并检查wp_set_auth_cookie是否正常工作。
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = true;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_set_auth_cookie( $user->ID, true );
} else {
echo $user->get_error_message();
}
我自己解决了这个问题。 api响应中存在一些未定义的变量错误。 这些错误与wp_set_auth_cookie()函数冲突。 当我修复代码中的错误时,502错误的门方式问题得到解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.