登录PHP时的Google Code身份验证错误

时间:2018-12-05 11:24:22

标签: php google-oauth2 google-authentication google-login google-authenticator

我正在尝试在我的PHP应用程序上实现Google登录,我遵循了所有Google说明以及示例代码。直到登录页面,它都可以正常工作。当我尝试验证从登录名获得的代码时会发生问题,因此它可以返回访问令牌。

这是我的oauth2callback.php文件。

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/includes/gmail/oauth2callback.php');

if (!isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();

  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {

 $client->authenticate($_GET['code']); //this is where the problem happens

  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/includes/gmail/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

我已经检查了“ $ _GET ['code']”是否正确,是否正确。我还跟踪了问题的根源在哪里,它使我进入了Google客户端类(Client.php)。

public function fetchAccessTokenWithAuthCode($code)
  {
    if (strlen($code) == 0) {
      throw new InvalidArgumentException("Invalid code");
    }

    $auth = $this->getOAuth2Service();
    $auth->setCode($code);
    $auth->setRedirectUri($this->getRedirectUri());

    $httpHandler = HttpHandlerFactory::build($this->getHttpClient());

    $creds = $auth->fetchAuthToken($httpHandler);//here is where it breaks

    if ($creds && isset($creds['access_token'])) {
      $creds['created'] = time();
      $this->setAccessToken($creds);
    }

    return $creds;
  }

所以我再次遵循了越野车功能,这导致我使用了以下OAuth2.php功能:

public function fetchAuthToken(callable $httpHandler = null)
    {
        if (is_null($httpHandler)) {
            $httpHandler = HttpHandlerFactory::build();
        }
        $pre_credentials = $this->generateCredentialsRequest();

        $response = $httpHandler($pre_credentials);//this is the root of the problem
        $credentials = $this->parseTokenResponse($response);
        $this->updateToken($credentials);

        return $credentials;
    }

在这里我无处可去,我不知道为什么httpHandler的auth出现问题,并且我无法继续登录。 这是httpHandler中唯一的方法:

public static function build(ClientInterface $client = null)
    {
        $version = ClientInterface::VERSION;
        $client = $client ?: new Client();

        switch ($version[0]) {
            case '5':
                return new Guzzle5HttpHandler($client);
            case '6':
                return new Guzzle6HttpHandler($client);
            default:
                throw new \Exception('Version not supported');
        }
    }

0 个答案:

没有答案