我最近从Apache Basic Auth迁移到了Google OAuth2。以前,$_SERVER['PHP_AUTH_USER']
过去是根据用户输入的信息设置的。现在我的页面页面显示使用google登录,$_SERVER['PHP_AUTH_USER']
未设置。我可以使用
<script>function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail())
但是我的访问控制是通过userdata。
例如。 if user == ABC =&gt;将他添加到白名单,
if user == XYZ =&gt;将他添加到黑名单等。在谷歌oauth之前,它是使用$_SERVER['PHP_AUTH_USER']
完成的。
虽然我有这些信息要在控制台中打印,但我需要这个来检查要向用户显示的内容和要隐藏的内容。谷歌没有关于如何使用此信息服务器端的信息。唯一的方法(我不认为正确的方法是将用户信息发回服务器)下面是我尝试设置$_SERVER variable
的代码,但似乎应该有更好的方法来做到这一点。即使这不起作用。
<script>function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var emailid = profile.getEmail();
//window.location.href = "myphpfile.php?name=" + emailid;//tried this aswell
$.ajax({
url: 'myphpfile.php',
type: 'post', // performing a POST request
data : {email:emailid},
dataType: 'text',
success: function(data)
{
console.log(data); //nothing gets printed here
}
在用户使用google登录之前,我还想显示任何内容。虽然这可以在以后完成。但目前我自己的用户限制失败,因为我无法找到谁是已登录的用户.myfile.php - &gt;
<?php
session_start();
$abc=$_POST['email'];
echo "$abc";
$_SESSION["PHP_AUTH_USER"] = $abc;
$_SERVER["PHP_AUTH_USER"] = $abc;
?>
我只需要获取电子邮件ID,看看是否应该为用户提供访问权限。
答案 0 :(得分:0)
在登录后使用ajax(实现回调)。谷歌为此提供了一个ajax脚本。
<!-- BEGIN Pre-requisites -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
您正在寻找的是in this google developer tutorial
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
答案 1 :(得分:0)
使用httprequests和curl
执行此操作的另一种方法<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="<YOURclientID>">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
function disassociate() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.disconnect().then(function () {
console.log('User disconnected from association with app.');
});
}
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server! Use idToken below
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://yourdomain/tokenIdRequest.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('NEW Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
console.log("ID Token: " + id_token);
};
</script>
</head>
<body>
<div id="login-button" class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<div><a href="#" onclick="signOut();">Sign out</a></div>
<div><a href="#" onclick="disassociate();">Disassociate App and Site (easily undone)</a></div>
</body>
</html>
并且接收php可以通过直接搜索googles api,发送一次性访问令牌并接收所有信息来解决问题。通过这种方式,您可以避免使用强力用户名黑客攻击
<?php
$inputRaw = file_get_contents('php://input');
$idToken= substr($inputRaw,8);
//$fp = fopen('twoStepOutput.txt', 'a');
//fwrite($fp, date("DATA: YmdHis")."\r\n$idToken\r\n");
$url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='.$idToken;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$json = json_decode($response, true);
curl_close($ch);
//fwrite($fp, "response:[$json]\r\n");
print_r($json); // sends answer back to JS frontend
//fclose($fp);
?>
答案 2 :(得分:0)
如果您仍然希望通过PHP执行此操作,请按以下步骤操作:
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setScopes(['email', 'profile']);
$oauth2Service = new Google_Service_Oauth2($client);
$userinfo = $oauth2Service->userinfo->get();
$print_r($userinfo); // => name, email, etc.