oauth 2.0-使用谷歌oauth2配置文件信息来设置$_SERVER php变量


oauth 2.0 - Using google oauth2 profile info to set $_SERVER php variables

我最近从Apache Basic Auth迁移到了Google OAuth2。以前,$_SERVER['PHP_AUTH_USER']用于根据用户输入的信息进行设置。现在我的页面显示了使用谷歌登录,$_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())

然而,我的访问控制是通过用户数据进行的。例如,如果用户==ABC=>将他添加到白名单中,如果用户==XYZ=>将他添加到黑名单等。在谷歌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
          } 

在用户登录谷歌之前,我也不想显示任何内容。尽管这可以稍后完成。但目前我自己的用户限制失败了,因为我无法找到登录的用户。myfile.php->

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

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

使用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可以通过直接搜索谷歌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);
?>

在签名后使用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 -->

你正在寻找的是解释在这个谷歌开发者教程

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

如果您仍然希望通过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.