使用Google一键进行PHP身份验证



我插入了"谷歌一键点击";在我的网站上,然后谷歌返回我";凭证";以及";g_ csrf_token";使用POST方法。现在我想知道,我是如何从这个";凭证";在PHP中?

Codeigniter 4有任何PHP库或模块吗?

我在前端只有这个:

<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload" data-client_id="000.apps.googleusercontent.com" data-login_uri="https://myweb.com/google"></div>

并且在后端文件"中;myurl/google";

print_r($_POST);

感谢

以下是如何获得它:

<?php
$token=$_POST["credential"];
print_r(json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1])))));
?>

我花了3天时间让它现在工作,谷歌的指南没有很好的记录:(.也许它会对某人有所帮助!

谷歌最近更新了";用于Web的Google Sign-In JavaScript平台库";用新的";Google Identity Services";,更多信息请点击此处:https://developers.google.com/identity/oauth2/web/guides/migration-to-gis

为此,用户可以更容易地使用云进行身份验证。

首先,您需要在这里生成简单的代码:https://developers.google.com/identity/gsi/web/tools/configurator.您将很容易地获得代码并将其放入HTML页面。你需要在上为我们服务

<div id="g_id_onload" data-locale="vi" data-callback="yourcallbackfunction"></div>

声明函数名称";您的回调函数(段落({}";,paras会给你两个重要的东西,客户ID和证书。

其次,您需要验证服务器上的token_id(它实际上是命名的证书(。也许是在你的callbackfunction函数上发布到你的服务器上。

此处记录:https://developers.google.com/identity/gsi/web/guides/verify-google-id-token

现在事情已经确定了。不要在意谷歌文档上的g_csrf_token。使用此调试工具https://oauth2.googleapis.com/tokeninfo?id_token=如果返回的是姓名、电子邮件、图片、潜艇等等…那么你可以继续。

第三,在您的服务器上。使用来自";Google API客户端库";参数示例:

$CLIENT_ID: 10493xxxxxxx-sjpa2xxxxxxxxxbo5hr3vvk4xxxxxx.apps.googleusercontent.com
$id_token: eyJhbGciOiJSUzI1NiIsImtpZCI6IjFhYWU4ZDdjOTIwNThiNWVlYTQ1Njg5NWJmODkwODQ1NzFlMzA2ZjMiLCJ0eXAiOiJKV1QifQ
require_once 'vendor/autoload.php';
// Get $id_token via HTTPS POST.
$client = new Google_Client(['client_id' => $CLIENT_ID]);  // Specify the CLIENT_ID of the app that accesses the backend
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
// If request specified a G Suite domain:
//$domain = $payload['hd'];
} else {
// Invalid ID token
}

不要忘记使用composer安装Google API。在这个步骤上;无效的ID令牌";如果时间已经过期。在我这边大约2分钟。

就是这样。它应该有效。

根据以下文档,以下是我们如何获得它:

此处

验证谷歌id令牌

图像1

这里:

服务器端集成

图像2

// Firstly, create Google client object with client ID
$google_client = new Google_Client([
'client_id' => YOUR_CLIENT_ID
]);
// Then, verify the credential
$token = $_POST['credential'];
$payload = $google_client->verifyIdToken($token);
if ($payload && $payload['aud'] == YOUR_CLIENT_ID)
{
// Here you can get user email from Google, Also you can get all user data
$email = $payload['email'];
// Lastly, you can add user email to session, Or any thing you want in your app
$_SESSION['user'] = $email;
}

最新更新