2015-07-01 79 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.