2015-08-29 82 views
0

我想要實現的是允許任何人登錄到該網站,並且只有經過許可的某個註冊用戶纔可以啓動「點按此按鈕...」我應該如何使用Google oAuth 2.0?

事情是,我非常不確定至於如何驗證用戶是否登錄並具有合法令牌來訪問該按鈕。我應該在客戶端的瀏覽器上存儲令牌並在按下按鈕時將其推送到服務器,這是否安全?

我應該在這種情況下使用PHP嗎?

我的主頁:

enter image description here

的Javascript & AJAX:

var token; 
function onSignIn(googleUser) { 
var profile = googleUser.getBasicProfile(); 
token = googleUser.getAuthResponse().id_token; // should I store the token? 

var form = { 
"ID": profile.getId(), 
    "Name": profile.getName(), 
    "Email": profile.getEmail(), 
    "Image_URL": profile.getImageUrl(), 
} 
$.ajax({ 
    method: "POST", 
    url: "php/verification.php", // register account and save to db. 
    data: form, 
    dataType: "json", 
    success: function(data) { 
     console.log(data.result) 
    } 
}) 
} 

我也很模糊與文檔: https://developers.google.com/identity/sign-in/web/backend-auth

會很開心如果有什麼人ld啓迪我的道路,並清除我的沮喪。

回答

0

是的,這是在鏈接的文檔中推薦的方法。

由於您使用的是PHP,因此您將使用Google's PHP SDK驗證令牌。這裏有一個簡單的例子:

/* Create the client, and add your credentials */ 
$client = new Google_Client(); 
$client->setClientId('your_client_id'); 
$client->setClientSecret('your_client_secret'); 

/* Verify the token you received */ 
$ticket = $client->verifyIdToken($_POST['token']); 

/* Get the response details */ 
$data = $ticket->getAttributes(); 

/* Retrieve user's unique Google ID */ 
echo json_encode(['user_id' => $data['payload']['sub']]);