2016-07-06 152 views
1

我有一个简单的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; 

>

回答

0

我只是猜测这里,但我最好的选择是你没有正确配置承载的令牌头(OneLogin不喜欢之后的最终的空间“:”且将其解释为承载标记的一部分)

所以,你应该尝试

$bearer_token = "Authorization: Bearer:". $a_token; // no space after Bearer: 
+0

嗨,约翰......谢谢......但那并没有解决它! – skyfullofstars

+0

然后这是一个PHP编码问题,我猜。 在这一点上,它看起来更像是一个编码错误,而不是API的问题。 最好的选择将是 一)检查你要回来,只是为了确保它被解析出正确 B)创建一个新的请求对象的第二请求例如承载令牌 $ ch2 = curl_init('https://api.us.onelogin.com/api/1/users'); 由于您正在重复使用第一个请求,它可能仍然被设置为执行POST(第二个端点是GET),并可能与第一个请求中遗留的其他选项混杂在一起。更好地从一个干净的石板开始 –

+0

a)是的。尝试过......被解析并正确发送到下一个函数。 b)创建新的请求对象$ ch2 .....注意这也失败了我的POST请求!.......没有工作! – skyfullofstars

0

鉴于我的第一个答案的失败...

检查你要回来,只是为了确保它被解析出正确

创建一个新的请求对象的第二请求例如承载令牌

$ch2 = curl_init('api.us.onelogin.com/api/1/users'); 

curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch2, CURLOPT_HTTPHEADER, array($bearer_token)); 

既然你打算重用的第一个请求,它可能仍然被设置为做一个POST(即第2个端点是GET),并可能与从第一次请求遗留下来的其它选项混乱。

+0

试过..didnt工作.....请参阅上文! – skyfullofstars

+0

尝试在用户端点上执行GET操作 - 它不支持POST(除非它是修改用户,在这种情况下语法不同,并且您必须使用允许读取/写入访问的凭据) –

+0

请阅读最初的帖子仔细!我提到GET和POST请求都不起作用。我有api凭证的管理用户权限.....以及我的命令在终端上正常工作! – skyfullofstars

0

这会导致你的问题

if(!curl_exec($ch)){ 
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch)); 
} 

您使用curl_exec两次!