php - 未经身份验证权限在 PHP 中使用 Google Oauth 登录
问题描述
我正在使用https://github.com/googleapis/google-api-php-client/releases
源文件:https ://github.com/googleapis/google-api-php-client/archive/v2.4.0.zip
获取用户详细信息Username, email, profile picture, user ID, access token, refresh token so on
,我能够通过用户身份验证权限获取所有详细信息并将其保存到我的数据库中。
Google_config.php
require_once 'Google/autoload.php';
//require_once 'client.json';
session_start();
$client = new Google_Client();
$client->setApplicationName("Login with Google Account");
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://localhost:8000/ads/login/redirect.php');
//$client->setAuthConfig("client.json");
$client->addScope([
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"
]);
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");
重定向.php
if (isset($_SESSION['accessToken'])) {
$client->setAccessToken($_SESSION['accessToken']);
} else if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$_SESSION['accessToken'] = $access_token;
} else {
header('location : index.php');
}
$oauth = new Google_Service_Oauth2($client);
if ($client->getAccessToken()) {
// Get user profile data from google
$gpUserProfile = $oauth->userinfo->get();
// Initialize User class
$user = new User();
// Getting user profile info
$gpUserData = array();
$gpUserData['oauth_uid'] = !empty($gpUserProfile['id']) ? $gpUserProfile['id'] : '';
$gpUserData['first_name'] = !empty($gpUserProfile['given_name']) ? $gpUserProfile['given_name'] : '';
$gpUserData['last_name'] = !empty($gpUserProfile['family_name']) ? $gpUserProfile['family_name'] : '';
$gpUserData['email'] = !empty($gpUserProfile['email']) ? $gpUserProfile['email'] : '';
$gpUserData['gender'] = !empty($gpUserProfile['gender']) ? $gpUserProfile['gender'] : '';
$gpUserData['locale'] = !empty($gpUserProfile['locale']) ? $gpUserProfile['locale'] : '';
$gpUserData['picture'] = !empty($gpUserProfile['picture']) ? $gpUserProfile['picture'] : '';
$gpUserData['link'] = !empty($gpUserProfile['link']) ? $gpUserProfile['link'] : '';
// Insert or update user data to the database
$gpUserData['oauth_provider'] = 'google';
$userData = $user->checkUser($gpUserData);
// Storing user data in the session
$_SESSION['userData'] = $userData;
// Render user profile data
if (!empty($userData)) {
$output = '<h2>Google Account Details</h2>';
$output .= '<div class="ac-data">';
$output .= '<img src="' . $userData['picture'] . '">';
$output .= '<p><b>Google ID:</b> ' . $userData['picture'] . '</p>';
$output .= '<p><b>Google ID:</b> ' . $userData['oauth_uid'] . '</p>';
$output .= '<p><b>Name:</b> ' . $userData['first_name'] . ' ' . $userData['last_name'] . '</p>';
$output .= '<p><b>Email:</b> ' . $userData['email'] . '</p>';
$output .= '<p><b>Gender:</b> ' . $userData['gender'] . '</p>';
$output .= '<p><b>Locale:</b> ' . $userData['locale'] . '</p>';
$output .= '<p><b>access token:</b> ' . $client->getAccessToken() . '</p>';
$output .= '<p><a href="' . $userData['link'] . '" target="_blank">Click to visit Google+</a></p>';
$output .= '<p>Logout from <a href="logout.php">Google</a></p>';
$output .= '</div>';
} else {
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
} else {
// Get login url
$authUrl = $client->createAuthUrl();
// Render google login button
$output = '<a href="' . filter_var($authUrl, FILTER_SANITIZE_URL) . '"><img src="images/google-sign-in-btn.png" alt=""/></a>';
}
?>
<div class="container">
<!-- Display login button / Google profile information -->
<?php echo $output; ?>
</div>
现在我的问题是GOOGLE 登录是如何工作的,因为当我使用上述方法时,它会获得用户身份验证,然后返回用户信息。
当我尝试登录时,在https://stackoverflow.com/中的哪里,我能够使用带有一些重定向的谷歌帐户登录。
我如何登录,也尝试了许多在线解决方案和谷歌文档。
任何解决方案都会有所帮助。
解决方案
最后是一个简单的解决方案:
if (isset($_GET['code'])) {
try {
$gapi = new GoogleLoginApi();
// Get the access token
$data = $gapi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $_GET['code']);
// Get user information
$user_info = $gapi->GetUserProfileInfo($data['access_token']);
} catch (Exception $e) {
echo $e->getMessage();
exit();
}
}
class GoogleLoginApi {
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://www.googleapis.com/oauth2/v4/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code=' . $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
throw new Exception('Error : Failed to receieve access token');
}
return $data;
}
public function GetUserProfileInfo($access_token) {
$url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
throw new Exception('Error : Failed to get user information');
}
return $data;
}
}
推荐阅读
- cygwin - 在非主文件夹中打开 Cygwin 终端时,如何阻止它忘记环境?
- python - 如何减小包含 python 实用程序的 nodejs 容器的大小
- sqlalchemy - flask_sqlalchemy 中具有相同表名的多数据库
- c# - 将属性名称作为字符串映射到对象
- android - 当类有 onTouchEvent 时如何使用 onCLick
- arrays - 执行 .Then() 承诺 NodeJS
- c - 在 Keil 中使用 gnu 工具链编译库
- android - 在 iOS 和 Android 的颤振项目中运行 firebase 的最低版本是什么?
- ruby-on-rails - 如何使用 Nokogiri 解析 Google 搜索页面以获取结果统计信息和 AdWords 计数
- acumatica - 用 Acumatica 模板中的自定义字符串替换空白字段