【问题标题】:PHP OAUTH2 "error":"invalid_grant","error_description":"The specified authorization code cannot be used by this client application."PHP OAUTH2 "error":"invalid_grant","error_description":"指定的授权码不能被这个客户端应用程序使用。"
【发布时间】:2021-07-28 04:55:00
【问题描述】:

我正在使用 oauth2 在 php 应用程序中设置授权,并且正在努力取回访问令牌。我收到错误 {"error":"invalid_grant","error_description":"指定的授权码不能被这个客户端应用程序使用。"} 我在任何地方都找不到这个错误的证据。我想这个错误可能来自不匹配的返回 url,但由于我的来自同一个变量,我不确定这是怎么回事。

这是我的代码:


if(isset($_POST['code'])){

    $access_token = getAccessToken($_POST["code"]);
    
    $resource = getResource($access_token);
    


}else if(!isset($_POST['code'])){
    header( "Location: https://growthzoneapp.com/oauth/authorize?client_id=$CLIENT_ID &response_type=code&response_mode=form_post&redirect_uri=$REDIRECT_URI&scope=openid+profile"
);
}


function getAccessToken($authorization_code) {
 global $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;


 $content = "grant_type=authorization_code&code=$authorization_code&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&redirect_uri=$REDIRECT_URI";



$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'https://growthzoneapp.com/oauth/token',
 CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>  $content  ,
CURLOPT_HTTPHEADER => [
    "content-type: application/x-www-form-urlencoded"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}



}

【问题讨论】:

  • invalid_grant 基本上意味着您传递给oauth/token 端点的authorization_code 无效或已过期。有关详细说明,请参阅 OAuth RFC (tools.ietf.org/html/rfc6749)。从您的代码中,不清楚您发送的授权代码来自何处,因此您需要提供更多详细信息。

标签: php oauth-2.0 access-token


【解决方案1】:

当授权请求中的客户端 ID 与访问令牌请求中的客户端 ID 不匹配时,会发生此错误。在这种情况下,授权请求“$CLIENT_ID &”中添加了一个额外的空格:

 header( "Location: https://growthzoneapp.com/oauth/authorize?client_id=$CLIENT_ID &response_type=code&response_mode=form_post&redirect_uri=$REDIRECT_URI&scope=openid+profile"

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2015-09-17
    • 2014-09-05
    • 2015-02-09
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2012-11-11
    相关资源
    最近更新 更多