使用google oauth2 profile info设置$\u服务器php变量

使用google oauth2 profile info设置$\u服务器php变量,php,oauth-2.0,google-signin,Php,Oauth 2.0,Google Signin,我最近从Apache Basic Auth迁移到Google OAuth2。以前,$\u服务器['PHP\u AUTH\u USER']用于根据用户输入的信息进行设置。现在我的页面显示了登录google,$\u服务器['PHP\u AUTH\u USER']没有设置。我可以在控制台上使用 <script>function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log

我最近从Apache Basic Auth迁移到Google OAuth2。以前,
$\u服务器['PHP\u AUTH\u USER']
用于根据用户输入的信息进行设置。现在我的页面显示了登录google,
$\u服务器['PHP\u AUTH\u 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())
我也不想显示任何东西,直到用户登录谷歌。虽然这可以稍后再做。但目前我自己的用户限制失败,因为我无法找到谁是已登录的用户。myfile.php->

<?php
session_start();
$abc=$_POST['email'];
echo "$abc";
$_SESSION["PHP_AUTH_USER"] = $abc;
$_SERVER["PHP_AUTH_USER"] = $abc;
?>

我只需要获取电子邮件id,看看是否应该向用户提供访问权限。

在登录后使用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 -->

你要找的是解释


函数signInCallback(authResult){
if(authResult['code']){
//现在用户已获得授权,请隐藏“登录”按钮,例如:
$('signinButton').attr('style','display:none');
//将代码发送到服务器
$.ajax({
键入:“POST”,
网址:'http://example.com/storeauthcode',
contentType:'应用程序/八位字节流;字符集=utf-8',
成功:功能(结果){
//处理或验证服务器响应。
},
processData:false,
数据:authResult['code']
});
}否则{
//有一个错误。
}
}
在登录后使用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 -->

你要找的是解释


函数signInCallback(authResult){
if(authResult['code']){
//现在用户已获得授权,请隐藏“登录”按钮,例如:
$('signinButton').attr('style','display:none');
//将代码发送到服务器
$.ajax({
键入:“POST”,
网址:'http://example.com/storeauthcode',
contentType:'应用程序/八位字节流;字符集=utf-8',
成功:功能(结果){
//处理或验证服务器响应。
},
processData:false,
数据:authResult['code']
});
}否则{
//有一个错误。
}
}

使用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>

函数签出(){
var auth2=gapi.auth2.getAuthInstance();
auth2.signOut().then(函数(){
log('User signed out');
});
}
函数解除关联(){
var auth2=gapi.auth2.getAuthInstance();
auth2.disconnect().then(函数(){
log('用户已断开与应用程序的关联');
});
}
函数onSignIn(谷歌用户){
//客户端脚本的有用数据:
var profile=googleUser.getBasicProfile();
console.log(“ID:+profile.getId());//不要直接将其发送到服务器!使用下面的idToken
log(“Name:+profile.getName());
log(“图像URL:+profile.getImageUrl());
log(“Email:+profile.getEmail());
//需要传递到后端的ID令牌:
var id_token=googleUser.getAuthResponse().id_token;
var xhr=new XMLHttpRequest();
xhr.open('POST','http://yourdomain/tokenIdRequest.php');
setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onload=函数(){
log('newsignedas:'+xhr.responseText);
};
send('idtoken='+id_token);
日志(“ID令牌:+ID_令牌”);
};
接收php可以通过直接搜索Google 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);
?>

使用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>

函数签出(){
var auth2=gapi.auth2.getAuthInstance();
auth2.signOut().then(函数(){
log('User signed out');
});
}
函数解除关联(){
var auth2=gapi.auth2.getAuthInstance();
auth2.disconnect().then(函数(){
log('用户已断开与应用程序的关联');
});
}
函数onSignIn(谷歌用户){
//客户端脚本的有用数据:
var profile=googleUser.getBasicProfile();
console.log(“ID:+profile.getId());//不要直接将其发送到服务器!使用下面的idToken
log(“Name:+profile.getName());
log(“图像URL:+profile.getImageUrl());
log(“Email:+profile.getEmail());
//需要传递到后端的ID令牌:
var id_token=googleUser.getAuthResponse().id_token;
var xhr=new XMLHttpRequest();
xhr.open('POST','http://yourdomain/tokenIdRequest.php');
setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onload=函数(){
log('newsignedas:'+xhr.responseText);
};
send('idtoken='+id_token);
日志(“ID令牌:+ID_令牌”);
};
接收php可以通过直接搜索Google 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);
?>

如果您仍然希望通过PHP实现这一点,下面介绍如何:

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setScopes(['email', 'profile']);
{}


如果您仍然希望通过PHP实现这一点,下面介绍如何:

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setScopes(['email', 'profile']);
{}


当所有身份验证逻辑都存在于服务器端时,为什么要使用客户端身份验证?您可以从服务器与OAuth API集成