使用 PHP cURL 向 Google Auth 进行身份验证会导致持续转发

Authenticating to Google Auth with PHP cURL causes continuously forwarding

我想从 Google OAuth 2.0 中检索 Auth 令牌(我使用了 this 教程) 但是,当我想要进行身份验证时,它会导致无限循环重定向到任何内容,从而刷新页面。没有任何错误信息。我不知道出了什么问题。

这是我的 PHP 代码:

<?php

// Admin Google API settings
// Portal url:

require_once('./curl.php');

define("CALLBACK_URL", "http://localhost/losapi/index2.php");  //Callback URL
define("AUTH_URL", "https://accounts.google.com/o/oauth2/v2/auth");   //Used to get CODE (not Token!)
define("CLIENT_ID", "***");  // Personal
define("CLIENT_SECRET", "***");  // Personal
define("SCOPE", "https://www.googleapis.com/auth/admin.directory.device.chromeos https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.orgunit"); // Depends on what you want to do.
define("APIURL_DIRECTORY","https://www.googleapis.com/admin/directory/v1/customer/");  // For Google Directory actions
define("CUSTOMER_ID","***");       // Personal
define("TOKEN_URL","https://oauth2.googleapis.com/token");   // URL to get Token (not code).
$curl = new \CURL\cURL();
// Initiate code for access token
if(isset($_GET["code"])){
  //DEBUG:  echo "Code: ".$_GET["code"];
  $url = TOKEN_URL."?";
  $url .= "code=".$_GET["code"];
  $url .= "&grant_type=authorization_code";
  $url .= "&client_id=". urlencode(CLIENT_ID);
  $url .= "&client_secret=". urlencode(CLIENT_SECRET);
  $url .= "&redirect_uri=". urlencode(CALLBACK_URL);

  $response = json_decode($curl->exeCurl($url,"POST"), true);
  if(isset($response)){
    if(array_key_exists("access_token", $response)) {
      $access_token = $response;
      setcookie("LOStoken", $response['access_token'], time() + (86400 * 30), "/");  // 86400 = 1 day
    }
  }
} else {

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

    $url = AUTH_URL."?";
    $url .= "response_type=code";
    $url .= "&client_id=". urlencode(CLIENT_ID);
    $url .= "&scope=". urlencode(SCOPE);
    $url .= "&redirect_uri=". urlencode(CALLBACK_URL);
    echo $curl->exeCurl($url,"GET");
  }
}

?>

curl.php

 namespace CURL;


class cURL
  {

// Algeneme cURL functie om web call te doen.
function exeCurl($url,$method,$body="") {
    $curl = curl_init();                      // initiate curl

    // Afhankelijk van TOKEN worden er andere headers gegeven.
    if(isset($_COOKIE["LOStoken"])){
        $headers = array(
            "Accept: */*",
            "Accept-Encoding: gzip, deflate",
            "Authorization: Bearer ". $_COOKIE["LOStoken"],
            "Connection: keep-alive",
            "Content-Length: ". strlen($body),
            "Content-Type: application/json",
            "cache-control: no-cache"
        );
    } else {
        $headers = array(
            "Accept: */*",

            "Cache-Control: no-cache",
            "Content-Length: ". strlen($body),
            "Connection: keep-alive",
            "cache-control: no-cache"
        );
    }

    // Set parameters for curl
    $params = array(
        CURLOPT_URL => $url,                              // API URL
        CURLOPT_RETURNTRANSFER => true,                   // Return answer
        CURLOPT_SSL_VERIFYPEER => false,                  // SSL, enable in production
        //CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,                          // Max redirect
        CURLOPT_FOLLOWLOCATION => true,                   // If 301, follow redirect
        CURLOPT_TIMEOUT => 30,                            // Max timeout
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,    // HTTP version used
        CURLOPT_CUSTOMREQUEST => $method,                 // HTTP method used
        CURLOPT_HTTPHEADER => $headers);                   // HTTP headers

    // Combineer curl + parameters
    curl_setopt_array($curl, $params);

    // Curl antwoorden
    $response = curl_exec($curl);
    $err = curl_error($curl);         // vul met errors
    curl_close($curl);                // Sluit verbinding

    if ($err) {
        echo "cURL Error #:" . $err;    // Als er errors zijn
    }
    if(array_key_exists("error", $response)) echo $response["error_description"];

    return $response;                 // Geef volledige antwoord terug
}


 }

您正在尝试通过 cURL 获取授权 URL - 这行不通,此授权流程需要用户交互。您需要在用户的浏览器中将用户重定向到此 URL。

您可以自动将用户重定向到 URL;或者您只需将它放入 link 的 href 属性中,这样用户就可以点击它,开始整个过程​​。 (我通常会推荐第二个选项,但至少在开发期间是这样。使用自动重定向,如果出现任何问题,您很有可能会再次创建循环重定向。)