首页 > 解决方案 > Google OAuth“错误 403:org_internal”,允许用户选择另一个登录

问题描述

我正在处理这个简短的代码片段来管理用户登录。我只需要验证用户身份并获取他的登录电子邮件地址。

我将应用程序设置为仅接受内部登录,但是(在测试时)如果我错误地使用了通用的@gmail.com 登录,我会收到一条错误消息,我无法从中退出。

我希望流程是询问登录 -> 输入的登录名来自错误的域 -> 再次询问

<?php

require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope('email');
$client->setApprovalPrompt("select-account");

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $service=new Google_Service_Oauth2($client);
  $user = $service->userinfo->get();

} else {
  $redirect_uri = 'http://mysite/book/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}



?>

为了完整起见,这是 oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setRedirectUri('http://mysite/book/oauth2callback.php');
$client->addScope('email');

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://mysite/book';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

谢谢

标签: phpoauthoauth-2.0google-oauth

解决方案


如果该用户存在,请使用 hd 参数尝试要求特定域用户:https ://developers.google.com/identity/protocols/oauth2/openid-connect#hd-param


推荐阅读