Integrating Google Sign-In into your web app
https://developers.google.com/identity/sign-in/web/people
Load the Google Platform Library
<script> src="https://apis.google.com/js/platform.js" async defer></script>
Specify your app’s client ID
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
Add a Google Sign-In button
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Get profile information
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()); // This is null if the 'email' scope is not present.
}
Sign out a user
<a href="#" onclick="signOut();">Sign out</a><script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
Getting profile information
!! 请勿使用getId()返回的Google ID或用户的个人资料信息将当前登录的用户传达给您的后端服务器。而是发送ID令牌,可以在服务器上对其进行安全验证
// auth2 is initialized with gapi.auth2.init() and a user is signed in.
if (auth2.isSignedIn.get()) {
var profile = auth2.currentUser.get().getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}
如果您只想登录用户,而无需获取用户ID以外的详细信息,则可以禁用检索基本配置文件信息,而仅请求配置文件范围
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
fetch_basic_profile: false,
scope: 'profile'
});
// Sign the user in, and then retrieve their ID.
auth2.signIn().then(function() {
console.log(auth2.currentUser.get().getId());
});
});
Authenticate with a backend server 后端验证用户
如果应用或网站将Google登录用于与后端服务器通信,则可能需要识别服务器上当前登录的用户。To do so securely, after a user successfully signs in, send the user’s ID token to your server using HTTPS. 然后,在服务器上,验证ID令牌的完整性,并使用令牌中包含的用户信息建立会话或创建新帐户
Send the ID token to your server
//After a user successfully signs in, get the user's ID token:
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
}
Verify the integrity of the ID token
Using a Google API Client Library
https://developers.google.com/identity/sign-in/web/backend-auth