2015-07-01 116 views
2

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

; 但是我的访问控制是通过userdata。 例如。如果用户== 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和用户是否应当提供访问与否。

+0

,为什么你会使用当你的所有认证逻辑都存在于服务器端时,客户端认证?您可以与服务器中的OAuth API集成。 –

+0

以前我们不得不在服务器上以加密形式存储用户密码。所以每次用户更改密码时,我们都必须进行更改。但通过Google登录,密码检查由Google完成。我们只需要根据已登录的用户提供访问限制 – user1977867

+1

我了解您使用OAuth进行(第三方身份验证),但不知道为什么您会选择客户端JavaScript实现而不是您的实现服务器端。您的服务器端代码可以处理与Google的API集成,这样您的服务器就可以检查响应并应用适当的权限。 –

回答

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

另一种方式来做到这一点使用HTTPRequests的和卷曲

<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); 
?> 
0

如果你还在寻找通过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.