Google API PHP登录检索身份验证错误

时间:2018-11-22 19:52:40

标签: php oauth-2.0 google-api google-oauth google-plus

我试图在我的应用程序上通过Google实现登录,以访问一些信息并控制用户Youtube频道的某些功能,但是它一直在返回错误,表明用户未通过身份验证。

那是我的代码。

<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'vendor/autoload.php';

$OAUTH2_CLIENT_ID = '-----------------------------------------';
$OAUTH2_CLIENT_SECRET = '-----------------';
$REDIRECT = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$APPNAME = "Test";

try{
    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setScopes([
        'https://www.googleapis.com/auth/youtube.force-ssl',
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/plus.me',
        'https://www.googleapis.com/auth/userinfo.profile'
    ]);
    $client->setRedirectUri($REDIRECT);
    $client->setApplicationName($APPNAME);
    $client->setDeveloperKey('---------------------');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
}
catch(Exception $e){
    die('1: '.$e);
}

$youtube = new Google_Service_YouTube($client);
$google_oauth = new Google_Service_Oauth2($client);
$plusAuth = new Google_Service_Plus($client);

if (isset($_GET['code'])) { 
    if (strval($_SESSION['state']) !== strval($_GET['state'])) {
        die('The session state did not match.');
    }

    try{
        $client->authenticate($_GET['code']);

        $user_email = $google_oauth->userinfo->get()->email;
        $user_name = $plusAuth->people->get('me')->displayName;
    }
    catch(Exception $e){
        die('2: '.$e);
    }

    // Code in between

    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    //echo "Access Token: " . json_encode($_SESSION['token']);

    header('Location: /main.php');
}


if ($client->getAccessToken()) {
    $_SESSION['token'] = $client->getAccessToken();
} 
else{
    $state = mt_rand();
    $client->setState($state);
    $_SESSION['state'] = $state;

    header('Location: '.$client->createAuthUrl());
}
?>

我收到此错误:

2: Google_Service_Exception: { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "domain": "global", "reason": "unauthorized" } ], "status": "UNAUTHENTICATED" } }

我找不到登录流程失败的原因,但是当它尝试使用Google Service Class的属性时,总是表示我未通过身份验证。

如果您能帮助我,我非常欢迎。

0 个答案:

没有答案