我正在构建一个小型API,并希望使用oAuth2.0进行登录和令牌处理。
我按照以下分步指南开始:https://bshaffer.github.io/oauth2-server-php-docs/cookbook/
现在这一切都很好,我可以通过从上面的链接指南向token.php发送帖子请求来获得我的access_token
:
//GET TOKEN
$params = array(
"client_id" => "testclient",
"client_secret" => "testpass",
"grant_type" => "client_credentials");
$test=curl_req($pageURL."/api/v1/"."token.php", $params, "POST");
echo "<pre>";
print_r($test);
该输出,具体如下:
stdClass Object ( [access_token] => b53a01a66d20760a8afef05bf36951eeba6b886d [expires_in] => 3600 [token_type] => Bearer [scope] => )
现在我有了令牌,并想请求resource.php,如上面的示例链接所示。但我想使用POST
,而不是像上面的分步指南链接中那样使用GET
。
是否可以用POST
验证access_token
?如果可以,如何验证?
示例中的命令是:
curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'
它实际上会发出POST,因为如果提供了"-d"标志,CURL将恢复为HTTP POST,请参阅http://curl.haxx.se/docs/manpage.html
通常,如果以任何标准化方式发送,OAuth服务器将能够拾取令牌,因此a)在"access_token"POST参数中,b)在"access_token"查询参数(GET)中,或c)在"Authorization:bearer"标头中。最后一个选项实际上是首选方法,因为它可以防止access_token与用户数据混合(即也适用于非REST环境)或最终出现在日志中。
我最终以这种方式发送了access_token和POST数据
$params = array(
"client_id" => "testclient",
"client_secret" => "testpass",
"grant_type" => "client_credentials");
//GET TOKEN
$test=curl_req($pageURL."/api/v1/"."token.php", $params, "POST");
// ^-- Im not using the curl_req2 function below here
// Im using a function, from my old question here: https://stackoverflow.com/questions/13420952/php-curl-delete-request
echo "<pre>";
print_r($test);
$token = array(
"access_token" =>$test->access_token);
$data = array(
"Some" =>"data",
"More" =>"datatatat"
);
// GET ACCESS using POST and POST data
$test2=curl_req2($pageURL."/api/v1/User.php",$token, $data , "POST");
print_r($test2);
function curl_req2($url,$token,$data,$req)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token['access_token']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//$result = json_decode($result);
curl_close($ch);
return $result;
}