【问题标题】:Using google oauth2 profile info to set $_SERVER php variables使用 google oauth2 配置文件信息设置 $_SERVER php 变量
【发布时间】:2015-09-18 16:33:04
【问题描述】:

我最近从 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())

; 但是我的访问控制是通过用户数据。 例如。如果用户 == ABC => 将他添加到白名单, 如果用户 == XYZ => 将他添加到黑名单等。在 google oauth 之前,它是使用 $_SERVER['PHP_AUTH_USER'] 完成的。

虽然我要在控制台中打印此信息,但我需要此信息来检查要向用户显示哪些内容以及要隐藏哪些内容。Google 上没有关于如何使用此信息服务器端的信息。唯一的方法(我认为不正确的方法是将用户信息发布回服务器)下面是我尝试设置$_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 ->

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

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

【问题讨论】:

  • 当您的所有身份验证逻辑都存在于服务器端时,为什么要使用客户端身份验证?您可以从服务器与 OAuth API 集成。
  • 以前我们必须在服务器上以加密形式存储用户密码。因此,每次用户更改密码时,我们都必须进行更改。但是使用谷歌登录,密码检查是由谷歌完成的。我们只需要根据已登录的用户提供访问限制
  • 我了解您将 OAuth 用于(第 3 方身份验证)什么,但不知道您为什么会选择客户端 javascript 实现而不是服务器端实现。您的服务器端代码可以处理与 Google 的 API 集成,这样您的服务器就有能力检查响应并应用适当的权限。
  • 是的,我无法在我的服务器上获取用户信息。这就是我的确切问题
  • @MikeBrant 实现登录客户端绝对更容易。更多可用的代码、更好的示例、更简单的工作流程。另一方面,具有客户端和服务器端操作的混合环境确实有其好处。在用户显式登录并开始他或她的活动后,客户端指示服务器端做一些后台工作。它确实有道理,尽管它肯定可以按照您的建议实现。

标签: php oauth-2.0 google-signin


【解决方案1】:

另一种使用 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】:

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

    【讨论】:

      【解决方案3】:

      如果您仍然希望通过 PHP 执行此操作,请按以下步骤操作:

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

      { authenticate... }

      $oauth2Service = new Google_Service_Oauth2($client);
      $userinfo = $oauth2Service->userinfo->get();
      $print_r($userinfo); // => name, email, etc.
      

      【讨论】:

        猜你喜欢
        • 2018-02-23
        • 2012-06-15
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 2010-10-11
        • 2013-01-02
        • 2020-01-31
        • 1970-01-01
        相关资源
        最近更新 更多