- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试创建一个基于网络的电子邮件客户端,它从谷歌邮件 API 获取所有电子邮件数据。我正在使用 Slim3 创建一个 Restful API 接口(interface)。要访问谷歌 API,我正在使用 Google-API-PHP-Client(谷歌确实有一个休息 API 访问权限,我真的很喜欢它,但我仍然没有弄清楚如果不使用 PHP-client-library 授权将如何工作).
我的主要问题是我如何构造其中的身份验证部分,因为谷歌使用 Oauth2 进行登录并提供代码。我可以在 Slim 中使用基于 token 的简单例份验证,但我该如何实现以下目标:
如何构建 API?
一种方法是使用谷歌的 token 作为应用程序中的唯一 token - 但它每小时都在变化,所以我如何通过 token 识别用户 - 为每个来电调用谷歌 API 似乎不是一个优雅的解决方案。
任何线索/链接都会非常有帮助。
提前致谢
最佳答案
注意有两部分:
我最近使用 Google 创建了这个非常轻量级的 Authorization 类,访问其 REST API。注释不言自明。
/**
* Class \Aptic\Login\OpenID\Google
* @package Aptic\Login\OpenID
* @author Nick de Jong, Aptic
*
* Very lightweight class used to login using Google accounts.
*
* One-time configuration:
* 1. Define what the inpoint redirect URIs will be where Google will redirect to upon succesfull login. It must
* be static without wildcards; but can be multiple as long as each on is statically defined.
* 2. Define what payload-data this URI could use. For example, the final URI to return to (the caller).
* 3. Create a Google Project through https://console.developers.google.com/projectselector/apis/credentials
* 4. Create a Client ID OAth 2.0 with type 'webapp' through https://console.developers.google.com/projectselector/apis/credentials
* 5. Store the 'Client ID', 'Client Secret' and defined 'Redirect URIs' (the latter one as defined in Step 1).
*
* Usage to login and obtain user data:
* 1. Instantiate a class using your stored Client ID, Client Secret and a Redirect URI.
* 2. To login, create a button or link with the result of ->getGoogleLoginPageURI() as target. You can insert
* an array of payload data in one of the parameters your app wants to know upon returning from Google.
* 3. At the Redirect URI, invoke ->getDataFromLoginRedirect(). It will return null on failure,
* or an array on success. The array contains:
* - sub string Google ID. Technically an email is not unique within Google's realm, a sub is.
* - email string
* - name string
* - given_name string
* - family_name string
* - locale string
* - picture string URI
* - hdomain string GSuite domain, if applicable.
* Additionally, the inpoint can recognize a Google redirect by having the first 6 characters of the 'state' GET
* parameter to be 'google'. This way, multiple login mechanisms can use the same redirect inpoint.
*/
class Google {
protected $clientID = '';
protected $clientSecret = '';
protected $redirectURI = '';
public function __construct($vClientID, $vClientSecret, $vRedirectURI) {
$this->clientID = $vClientID;
$this->clientSecret = $vClientSecret;
$this->redirectURI = $vRedirectURI;
if (substr($vRedirectURI, 0, 7) != 'http://' && substr($vRedirectURI, 0, 8) != 'https://') $this->redirectURI = 'https://'.$this->redirectURI;
}
/**
* @param string $vSuggestedEmail
* @param string $vHostedDomain Either a GSuite hosted domain, * to only allow GSuite domains but accept all, or null to allow any login.
* @param array $aPayload Payload data to be returned in getDataFromLoginRedirect() result-data on succesfull login. Keys are not stored, only values. Example usage: Final URI to return to after succesfull login (some frontend).
* @return string
*/
public function getGoogleLoginPageURI($vSuggestedEmail = null, $vHostedDomain = '*', $aPayload = []) {
$vLoginEndpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
$vLoginEndpoint .= '?state=google-'.self::encodePayload($aPayload);
$vLoginEndpoint .= '&prompt=consent'; // or: select_account
$vLoginEndpoint .= '&response_type=code';
$vLoginEndpoint .= '&scope=openid+email+profile';
$vLoginEndpoint .= '&access_type=offline';
$vLoginEndpoint .= '&client_id='.$this->clientID;
$vLoginEndpoint .= '&redirect_uri='.$this->redirectURI;
if ($vSuggestedEmail) $vLoginEndpoint .= '&login_hint='.$vSuggestedEmail;
if ($vHostedDomain) $vLoginEndpoint .= '&hd='.$vHostedDomain;
return($vLoginEndpoint);
}
/**
* Call this function directly from the redirect URI, which is invoked after a call to getGoogleLoginPageURL().
* You can either provide the code/state GET parameters manually, otherwise it will be retrieved from GET automatically.
* Returns an array with:
* - sub string Google ID. Technically an email is not unique within Google's realm, a sub is.
* - email string
* - name string
* - given_name string
* - family_name string
* - locale string
* - picture string URI
* - hdomain string G Suite domain
* - payload array The payload originally provided to ->getGoogleLoginPageURI()
* @param null|string $vCode
* @param null|string $vState
* @return null|array
*/
public function getDataFromLoginRedirect($vCode = null, $vState = null) {
$vTokenEndpoint = 'https://www.googleapis.com/oauth2/v4/token';
if ($vCode === null) $vCode = $_GET['code'];
if ($vState === null) $vState = $_GET['state'];
if (substr($vState, 0, 7) !== 'google-') {
trigger_error('Invalid state-parameter from redirect-URI. Softfail on login.', E_USER_WARNING);
return(null);
}
$aPostData = [
'code' => $vCode,
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectURI,
'grant_type' => 'authorization_code'
];
curl_setopt_array($hConn = curl_init($vTokenEndpoint), [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => defined('PROJECT_ID') && defined('API_CUR_VERSION') ? PROJECT_ID.' '.API_CUR_VERSION : 'Aptic\Login\OpenID\Google PHP-class',
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => 1
]);
curl_setopt($hConn, CURLOPT_POSTFIELDS, http_build_query($aPostData));
$aResult = json_decode(curl_exec($hConn), true);
curl_close($hConn);
if (is_array($aResult) && array_key_exists('access_token', $aResult) && array_key_exists('refresh_token', $aResult) && array_key_exists('expires_in', $aResult)) {
$aUserData = explode('.', $aResult['id_token']); // Split JWT-token
$aUserData = json_decode(base64_decode($aUserData[1]), true); // Decode JWT-claims from part-1 (without verification by part-0).
if ($aUserData['exp'] < time()) {
trigger_error('Received an expired ID-token. Softfail on login.', E_USER_WARNING);
return(null);
}
$aRet = [
// 'access_token' => $aResult['access_token'],
// 'expires_in' => $aResult['expires_in'],
// 'refresh_token' => $aResult['refresh_token'],
'sub' => array_key_exists('sub', $aUserData) ? $aUserData['sub'] : '',
'email' => array_key_exists('email', $aUserData) ? $aUserData['email'] : '',
'name' => array_key_exists('name', $aUserData) ? $aUserData['name'] : '',
'given_name' => array_key_exists('given_name', $aUserData) ? $aUserData['given_name'] : '',
'family_name' => array_key_exists('family_name', $aUserData) ? $aUserData['family_name'] : '',
'locale' => array_key_exists('locale', $aUserData) ? $aUserData['locale'] : '',
'picture' => array_key_exists('picture', $aUserData) ? $aUserData['picture'] : '',
'hdomain' => array_key_exists('hd', $aUserData) ? $aUserData['hd'] : '',
'payload' => self::decodePayload($vState)
];
return($aRet);
} else {
trigger_error('OpenID Connect Login failed.', E_USER_WARNING);
return(null);
}
}
protected static function encodePayload($aPayload) {
$aPayloadHEX = [];
foreach($aPayload as $vPayloadEntry) $aPayloadHEX[] = bin2hex($vPayloadEntry);
return(implode('-', $aPayloadHEX));
}
/**
* You generally do not need to call this method from outside this class; only if you
* need your payload *before* calling ->getDataFromLoginRedirect().
* @param string $vStateParameter
* @return array
*/
public static function decodePayload($vStateParameter) {
$aPayload = explode('-', $vStateParameter);
$aRetPayload = [];
for($i=1; $i<count($aPayload); $i++) $aRetPayload[] = hex2bin($aPayload[$i]);
return($aRetPayload);
}
}
一旦函数 getDataFromLoginRedirect
返回用户数据,您的用户就被授权。这意味着您现在可以发布自己的内部身份验证 token 。
因此,对于身份验证,维护您自己的用户数据表,使用sub
或email
作为主要标识符并为他们颁发 token ,具有适当的过期机制。 Google token 本身不一定要存储,因为它们仅在后续的 Google API 调用中需要;这取决于您的用例。不过,对于您自己的应用程序,您自己的 token 机制足以进行身份验证。
回到你的问题:
Google 的身份验证/授权。
如上所述。
识别新用户与回访用户。
可以通过你的数据表中用户的存在来判断。
维护和保留来自 google 和本地 API 的访问和刷新 token
问问自己是否真的需要。如果是这样,您可以在每 x 个请求时刷新,或者在到期时间少于 x 分钟后刷新(即,在这种情况下,这将是您的应用程序的超时)。如果你真的需要你的 token 保持有效,你应该设置一个守护进程机制来定期刷新你的用户 token 。
关于php - 如何使用 slim 3 Rest API 授权 google-api-php-client?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43973620/
我在 JavaScript 文件中运行 PHP,例如...... var = '';). 我需要使用 JavaScript 来扫描字符串中的 PHP 定界符(打开和关闭 PHP 的 )。 我已经知道使
我希望能够做这样的事情: php --determine-oldest-supported-php-version test.php 并得到这个输出: 7.2 也就是说,php 二进制检查 test.
我正在开发一个目前不使用任何框架的大型 php 站点。我的大问题是,随着时间的推移慢慢尝试将框架融入应用程序是否可取,例如在创建的新部件和更新的旧部件中? 比如所有的页面都是直接通过url服务的,有几
下面是我的源代码,我想在同一页面顶部的另一个 php 脚本中使用位于底部 php 脚本的变量 $r1。我需要一个简单的解决方案来解决这个问题。我想在代码中存在的更新查询中使用该变量。 $name)
我正在制作一个网站,根据不同的情况进行大量 PHP 重定向。就像这样...... header("Location: somesite.com/redirectedpage.php"); 为了安全起见
我有一个旧网站,我的 php 标签从 因为短标签已经显示出安全问题,并且在未来的版本中将不被支持。 关于php - 如何避免在 php 文件中写入
我有一个用 PHP 编写的配置文件,如下所示, 所以我想用PHP开发一个接口(interface),它可以编辑文件值,如$WEBPATH , $ACCOUNTPATH和 const值(value)观
我试图制作一个登录页面来学习基本的PHP,首先我希望我的独立PHP文件存储HTML文件的输入(带有表单),但是当我按下按钮时(触发POST到PHP脚本) )我一直收到令人不愉快的错误。 我已经搜索了S
我正在寻找一种让 PHP 以一种形式打印任意数组的方法,我可以将该数组作为赋值包含在我的(测试)代码中。 print_r 产生例如: Array ( [0] => qsr-part:1285 [1]
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: What is the max key size for an array in PHP? 正如标题所说,我想知道
我正在寻找一种让 PHP 以一种形式打印任意数组的方法,我可以将该数组作为赋值包含在我的(测试)代码中。 print_r 产生例如: Array ( [0] => qsr-part:1285 [1]
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 9 年前。 Improve this ques
我在 MySQL 数据库中有一个表,其中存储餐厅在每个工作日和时段提供的菜单。 表结构如下: i_type i_name i_cost i_day i_start i_
我有两页。 test1.php 和 test2.php。 我想做的就是在 test1.php 上点击提交,并将 test2.php 显示在 div 中。这实际上工作正常,但我需要向 test2.php
我得到了这个代码。我想通过textarea更新mysql。我在textarea中回显我的MySQL,但我不知道如何更新它,我应该把所有东西都放进去吗,因为_GET模式没有给我任何东西,我也尝试_GET
首先,我是 php 的新手,所以我仍在努力学习。我在 Wordpress 上创建了一个表单,我想将值插入一个表(data_test 表,我已经管理了),然后从 data_test 表中获取所有列(id
我有以下函数可以清理用户或网址的输入: function SanitizeString($var) { $var=stripslashes($var); $va
我有一个 html 页面,它使用 php 文件查询数据库,然后让用户登录,否则拒绝访问。我遇到的问题是它只是重定向到 php 文件的 url,并且从不对发生的事情提供反馈。这是我第一次使用 html、
我有一个页面充满了指向 pdf 的链接,我想跟踪哪些链接被单击。我以为我可以做如下的事情,但遇到了问题: query($sql); if($result){
我正在使用 从外部文本文件加载 HTML/PHP 代码 $f = fopen($filename, "r"); while ($line = fgets($f, 4096)) { print $l
我是一名优秀的程序员,十分优秀!