【发布时间】:2022-04-15 18:13:29
【问题描述】:
我需要连接使用 oAuth2 的 API。 我以前从未使用过 oAuth2,我不确定如何使用。 提供者提供此信息:
通过向上述端点发送 HTTP POST 请求来获取访问令牌。请求应包含以下标头:
Authorization: Basic [client_id]:[client_secret]
Content-Type: application/x-www-form-urlencoded
[client_id] 和 [client_secret] 应替换为您的信息。组合的[client_id]:[client_secret] 字符串应该是base64 编码的。
标题应该是这样的:
Authorization: Basic bXlfY2xpZW50X2lkOnBFUnkyTGhLYko0U2FkY3ZLcklpQW5xWnprakg5bm9STUc3aUxZcWl2MA==
最后,您需要以下请求正文:
grant_type=password&scope=read write&username=[username]&password=[password]
其中 [用户名] 和 [密码] 应替换为您的凭据。如果您使用 API 密钥访问 API,则应将 [用户名] 和 [密码] 替换为上面获得的 API 密钥。
如果您的请求组成正确,并且您的凭据正确,服务器将返回 JSON 格式的 access_token 供您使用:
{
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9(...)",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":null
}
我尝试了以下,但它返回了无效的请求消息:
$api = "KEY GOES HERE";
$authurl = "https://url.com/oauth/token";
$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";
// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);
$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";
$data = "grant_type=password&scope=read write&username=".$api."&password=".$api."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$auth = curl_exec( $ch );
if ( curl_errno( $ch ) ){
echo 'Error: ' . curl_error( $ch );
}
curl_close($ch);
$secret = json_decode($auth);
$access_key = $secret->access_token;
【问题讨论】:
-
让我们显示确切的错误信息。
-
我得到的是:{ "error": "invalid_request" }
-
为什么你使用了用户名和密码=api key?
-
因为提供者的指示。他们写道:如果您使用 API 密钥访问 API,则应将 [用户名] 和 [密码] 替换为上面获得的 API 密钥。所以我的理解是使用密钥作为用户名和密码?
-
您能否分享您尝试连接的位置?