我有一个简单的curl请求,以PHP编写的onelogin api。请求工作正常,从我的终端我的参数,我可以登录我的用户,但我在服务器上运行的PHP版本,生成访问令牌,但当我尝试任何GET或POST请求时,会出现401错误。我试过各种卷曲参数。一个html表单提交给lampp栈上的这个php页面。似乎没有工作。下面是一个简单的GET请求的PHP脚本。真的很感激有这方面的帮助:onelogin api with php curl 401未授权
<?php
//form will post these variables for post request
//$username = $_POST['uname'];
//$password = $_POST['pwd'];
$data = array("grant_type" => "client_credentials");
$data_string = json_encode($data);
$ch = curl_init('https://api.us.onelogin.com/auth/oauth2/token');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: client_id:XXX, client_secret:XXX",
"Content-Type: application/json")
);
//execute post
$result = curl_exec($ch);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
//parsse out bearer token and set header
$json = json_decode($result, true);
$a_token = $json['data'][0]['access_token'];
$bearer_token = "Authorization: bearer: ". $a_token;
curl_setopt($ch, CURLOPT_URL, "https://api.us.onelogin.com/api/1/users");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($bearer_token));
//execute
$result2 = curl_exec($ch);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
//close connection
curl_close($ch);
echo $result2;
>
嗨,约翰......谢谢......但那并没有解决它! – skyfullofstars
然后这是一个PHP编码问题,我猜。 在这一点上,它看起来更像是一个编码错误,而不是API的问题。 最好的选择将是 一)检查你要回来,只是为了确保它被解析出正确 B)创建一个新的请求对象的第二请求例如承载令牌 $ ch2 = curl_init('https://api.us.onelogin.com/api/1/users'); 由于您正在重复使用第一个请求,它可能仍然被设置为执行POST(第二个端点是GET),并可能与第一个请求中遗留的其他选项混杂在一起。更好地从一个干净的石板开始 –
a)是的。尝试过......被解析并正确发送到下一个函数。 b)创建新的请求对象$ ch2 .....注意这也失败了我的POST请求!.......没有工作! – skyfullofstars