php – 为什么我一直在为invalid_grant捕获Google_Auth_Exception?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 为什么我一直在为invalid_grant捕获Google_Auth_Exception?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5939字,纯文字阅读大概需要9分钟。
内容图文
![php – 为什么我一直在为invalid_grant捕获Google_Auth_Exception?](/upload/InfoBanner/zyjiaocheng/724/b16ed491c9e4448487f44a4b586a3f97.jpg)
我正在尝试构建一个访问Google AnalyticsAPI并提取数据的网络应用.但是,我在OAuth 2.0授权方面遇到了一些问题.
它允许成功的初始访问,但是当我点击刷新页面的提交按钮时,它会快速将我踢出并抛出Google_Auth_Exception,并显示错误“获取OAuth2访问令牌时出错,消息:’invalid_grant”.
据我了解OAuth 2.0,验证有4个步骤:
>从Google Dev Console获取OAuth 2.0凭据
>从Google Authorization Server获取访问令牌
>将访问令牌发送到Google AnalyticsAPI
>如有必要,刷新访问令牌
据我了解,$client-> setAccessToken();自动刷新令牌.
自从他们转移到Github之后,我似乎无法找到谷歌的任何文档,而且我大部分都遵循了他们的示例结构.
当它尝试执行$client-> authenticate($_ GET [‘code’])时,从第一个try块抛出错误;
我目前的解决方法是取消设置会话令牌,并让用户重新授权.但是,这非常麻烦和干扰,因为与页面的任何交互都会要求重新授权.
任何帮助将不胜感激!
这是我的代码:
<?php
/**********************
OAUTH 2.0 AUTHORIZATION
***********************/
//required libraries
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
//variables
$client_id = 'redacted';
$client_secret = 'redacted';
$redirect_uri = 'http://'.$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$dev_key = 'redacted';
//create a Google client
$client = new Google_Client();
$client->setApplicationName('App');
//sets client's API information
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($dev_key);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//if log out is requested, revoke the access
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
}
//check if authorization code is in the URL
try{
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']); //does authorization work
$_SESSION['access_token'] = $client->getAccessToken(); //gets valid access token
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //set into session storage
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); //cleans up the URL
}
}
//if the authorization code is now invalid
catch (Google_Auth_Exception $e) {
unset($_SESSION['token']); //unset the session token
echo "Token now invalid, please revalidate. <br>";
}
//if there is an access token in the session storage
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']); //set the client's access token
//try creating an analytics object
try {
$analytics = new Google_Service_Analytics($client);
echo 'Created Google Analytics Client successfully! <br><br>';
}
catch (Google_Auth_Exception $e) {
echo 'Need authorization!';
}
} else {
$authUrl = $client->createAuthUrl(); //create one
echo "<a class='login' href='$authUrl'><button>Authorize Google Access</button></a>"; //print button
}
解决方法:
我解决了这个问题.我试图两次授权相同的身份验证代码,因此它返回了invalid_grant错误.
我的解决方案是重写大部分代码并修复OAuth2逻辑.
我在下面创建了OAuth2身份验证流程的迷你教程:
<?php
session_start(); // Create a session
/**************************
* Google Client Configuration
*
* You may want to consider a modular approach,
* and do the following in a separate PHP file.
***************************/
/* Required Google libraries */
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/* API client information */
$clientId = 'YOUR-CLIENT-ID-HERE';
$clientSecret = 'YOUR-CLIENT-SECRET-HERE';
$redirectUri = 'http://www.example.com/';
$devKey = 'YOUR-DEVELOPER-KEY-HERE';
// Create a Google Client.
$client = new Google_Client();
$client->setApplicationName('App'); // Set your app name here
/* Configure the Google Client with your API information */
// Set Client ID and Secret.
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
// Set Redirect URL here - this should match the one you supplied.
$client->setRedirectUri($redirectUri);
// Set Developer Key and your Application Scopes.
$client->setDeveloperKey($devKey);
$client->setScopes(
array('https://www.googleapis.com/auth/analytics.readonly')
);
/**************************
* OAuth2 Authentication Flow
*
* You may want to consider a modular approach,
* and do the following in a separate PHP file.
***************************/
// Create a Google Analytics Service using the configured Google Client.
$analytics = new Google_Service_Analytics($client);
// Check if there is a logout request in the URL.
if (isset($_REQUEST['logout'])) {
// Clear the access token from the session storage.
unset($_SESSION['access_token']);
}
// Check if there is an authentication code in the URL.
// The authentication code is appended to the URL after
// the user is successfully redirected from authentication.
if (isset($_GET['code'])) {
// Exchange the authentication code with the Google Client.
$client->authenticate($_GET['code']);
// Retrieve the access token from the Google Client.
// In this example, we are storing the access token in
// the session storage - you may want to use a database instead.
$_SESSION['access_token'] = $client->getAccessToken();
// Once the access token is retrieved, you no longer need the
// authorization code in the URL. Redirect the user to a clean URL.
header('Location: '.filter_var($redirectUri, FILTER_SANITIZE_URL));
}
// If an access token exists in the session storage, you may use it
// to authenticate the Google Client for authorized usage.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// If the Google Client does not have an authenticated access token,
// have the user go through the OAuth2 authentication flow.
if (!$client->getAccessToken()) {
// Get the OAuth2 authentication URL.
$authUrl = $client->createAuthUrl();
/* Have the user access the URL and authenticate here */
// Display the authentication URL here.
}
/**************************
* OAuth2 Authentication Complete
*
* Insert your API calls here
***************************/
希望这有助于将来陷入困境!
内容总结
以上是互联网集市为您收集整理的php – 为什么我一直在为invalid_grant捕获Google_Auth_Exception?全部内容,希望文章能够帮你解决php – 为什么我一直在为invalid_grant捕获Google_Auth_Exception?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。