- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试构建一个访问 Google Analytics API 并提取数据的网络应用程序。但是,我在 OAuth 2.0 授权方面遇到了一些问题。
它允许成功的初始访问,但它很快将我踢出并在我点击刷新页面的提交按钮时抛出带有消息“获取 OAuth2 访问 token 时出错,消息:‘invalid_grant’”的 Google_Auth_Exception。
据我了解 OAuth 2.0,身份验证有 4 个步骤:
据我了解,$client->setAccessToken();自动刷新 token 。
自从他们转移到 Github 后,我似乎无法从 Google 找到任何文档,而且我大部分时间都遵循了他们的示例结构。
错误从第一个 try block 中抛出,当它尝试执行 $client->authenticate($_GET['code']);
我当前的解决方法是取消设置 session token ,并让用户重新授权。然而,这确实很麻烦且具有侵入性,因为与该页面的任何交互都将要求重新授权。
如有任何帮助,我们将不胜感激!
这是我的代码:
<?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?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498104/
我将this tutorial应用到symfony 2.4中,我已经完成config.yml中的所有设置,我设法访问了admin / google / analytics页面,但问题是当我尝试使用我的
我正在尝试构建一个访问 Google Analytics API 并提取数据的网络应用程序。但是,我在 OAuth 2.0 授权方面遇到了一些问题。 它允许成功的初始访问,但它很快将我踢出并在我点击刷
我正在使用 google-api-client-php 库中的 user-example.php,它抛出了错误 Fatal error: Uncaught exception 'Google_Auth
我正在尝试对 Google Developer's website 中描述的 Google+ 网络登录服务器端流程进行细微改动。 . 我有一个员工登录页面 (staff_login.php),它通过
我正在尝试使用最新版本的google-api-php-client获取访问 token (请查看此https://github.com/google/google-api-php-client),并且
我正在尝试通过 gmail api 从 Google 获取邮件 在收到 token 后对 Google_Client 进行身份验证时出现此错误 fatal error :未捕获异常“Google_Au
我有一个预测应用程序,它基于最新的 Google-api-php 客户端版本 1.0.0。它在 localhost 环境中完美运行。但是当我将完全相同的应用程序部署到托管服务器环境中时,出现了以下问题
我是一名优秀的程序员,十分优秀!