使用 google 帐户访问私人网站

Using google account for private website access

目前,我正在为其开发的人使用 google 文档来显示 website/files。只能通过以特定域名结尾的 google 个帐户访问。例如 danny@webtest.com 如果它是一个 webtest google 帐户那么它可以访问它。

现在我正在为他们创建一个未链接到 google 的网站。但是,我还是需要这个认证过程。

第一步 登录页面将是一个简单的 "connect with google account"

第二步 用户被重定向到登录 google,如果他们已经登录,则转到下一步。

第三步 电子邮件地址与我的数据库进行交叉检查,如果为该用户的行 ID 创建了一个会话,如果没有则添加它。

我尽量保持简单,但我不知道在哪里或如何进行第二步。

使用OAuth2。 Google 将其用于身份验证过程。

OAuth 声明开放授权。 OAuth 是一种协议,旨在与 HTTP 一起使用,使访问令牌能够通过身份验证服务器向第三方客户端发布,并获得用户的批准。

OAuth 开始被弃用,各大公司都开始使用 OAuth2 协议,这是 OAuth 的改进版本,但不幸的是它不向后兼容。

您可以在 PHP 中找到多个实现,例如 this one

看完@Izzy提到的维基百科介绍,你可以看看at google's Oauth2 introduction and then jump into google's quick start sample app;它提供了一个完整的评论 php 应用程序,该应用程序使用 oauth 2.0 通过 google 帐户进行身份验证并获取用户数据。

示例中的代码使用包 google-api-php-client 以及一个 js 库来将样板简化为更简单的 API 调用。对于 client/frontend 端,javascript 调用如:

auth2.signIn().then(function(googleUser) {
  onSignInCallback(googleUser.getAuthResponse());
}, function(error) {
  alert(JSON.stringify(error, undefined, 2));
});

并且在服务器上,php端:

$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());

// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
    ->getAttributes();
$gplus_id = $attributes["payload"]["sub"];

// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);

请注意,请求电子邮件地址需要进一步请求许可(名为 Authorization scopes) from the client, as seen in this SO question:

$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));

然后您可以使用任意数量的 APIs that expose userinfo.email。其中之一 Google_Service_Oauth2 具有有用的 public 方法 userinfo

$oauth2Service = new Google_Service_Oauth2(...);
$userinfo = $oauth2Service->userinfo;