2015-08-29 86 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']]);