我想使用 keycloak 进行用户授权,我发送了一个 get 请求access_token,但收到错误Missing form parameter: grant_type,这意味着缺少正确的标头Content-Type(需要该值application/x-www-form-urlencoded)。
代码
public function login(Request $req) {
$url = env('KEYCLOAK_HOST').'/auth/realms/'.env('KEYCLOAK_REALM').'/protocol/openid-connect/token';
$options = [
'client_id' => env('KEYCLOAK_CLIENT_ID'),
'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
'grant_type' => env('KEYCLOAK_GRANT_TYPE'),
'username' => $req->username,
'password' => $req->password,
'scope' => 'openid'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
return response(['res' => json_decode($response), 'err' => json_decode($error)], 200)
->header('Content-Type', 'application/json');
}
如何正确设置标题Content-Type的值application/x-www-form-urlencoded?
也许这就是问题所在:
https://www.php.net/manual/en/function.curl-setopt.php 注意:当传递数组 CURLOPT_POSTFIELDS 时,数据将被编码为 multipart/form-data ,当传递 URL 编码字符串时,数据将被编码为编码为 application/x-www-form-urlencoded
如果我理解正确,对于 application/x-www-form-urlencoded 您需要删除:
表格字段: