问题
I'am working on a REST API. Therefore I prepared a function which sends the authentication data via curl to the REST Server. I've implemented two authentication options. The first is Basic Authentication, the second is authentication via token (Bearer).
Now, i'am in trobles, because at the REST Server, the POST Data is not received by the REST Server in case of authentication via token. The authentication itself is working, but the POST Data is going to be lost. In case of authentication via Basis Authentication, the POST Data will be received by the REST Server, no problem.
private function request($postdata){
$url = $this->service_url_private;
$curl = curl_init($url);
$curl_post_data = $postdata;
// check if token authentication is used
if (array_key_exists('token', $postdata )){
$token = $postdata['token'];
$authorization = 'Authorization: Bearer ' . $token;
// prepare curl for Bearer Token Authorization
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization));
} else {
// otherwise use BASIC authentication
if (array_key_exists('email', $postdata )){
$username = $postdata['email'];
}
if (array_key_exists('password', $postdata )){
$password = $postdata['password'];
}
// prepare curl for Basic Authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLINFO_HEADER_OUT, true); // Detail information for debugging
curl_setopt($curl, CURLOPT_VERBOSE,true);
$curl_response = curl_exec($curl); // Detail information for debugging
$info = curl_getinfo($curl); // Detail information for debugging
curl_close($curl);
var_dump($info);
return $curl_response;
}
In addition, $curl_post_data is showing all the data by the client while debugging, before the rest call will be executed with curl_exec($curl).
What could be the problem?
回答1:
After lots of hours I found the problem and the solution for this problem.
The problem is:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization));
Using 'Content-Type: application/json' results in loosing the POST data information.
Solution for this is:
change
'Content-Type: application/json'
to
'Content-Type: application/x-www-form-urlencoded'
回答2:
You can use yii2's HttpBasicAuth authenticator behaviour for bearer token auth.
use yii\filters\auth\HttpBasicAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
Authentication
For the solution you were suggesting, you should use json request parser.
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
JsonParser
来源:https://stackoverflow.com/questions/49736998/yii2-rest-authentication-bearer-post-data-missing