Here's how I do it, after getting the signin's client file :
// HTML
<script type='text/javascript' src="https://apis.google.com/js/api:client.js" async defer></script>
I called gapi.load()
function into a HTML button
// load the startApp function after the page loads
jQuery(function () {
$(window).load(function () {
startApp()
})
})
var startApp = function () {
gapi.load('auth2', function () {
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: 'xxxxxxxx-xxxxxxxxxx.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
ux_mode: 'redirect', // I don't want it to display a pop-up
scope: 'profile email' // I just need to get user's name, profile picture and email address
});
// attach this function into a button element with id = "customBtn"
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function (googleUser) {
// it never calls this block of code.
// this never runs
console.log(googleUser.getBasicProfile().getName())
var gProfile = googleUser.getBasicProfile();
var name = gProfile.getName();
var email = gProfile.getEmail();
var imgUrl = gProfile.getImageUrl();
}, function (error) {
return alert("Google Sign in error!")
});
}
It load the necessary functions into a button. If user click on that button, user will be redirected into Google's signin page. After user manages to sign in then Google will redirect the URL back into my website.
It should also send the user's profile info into my attachClickHandler()
function within the attachSignin()
. But it never happens since it reloads the page before the handler function gets called. It only works if I change the ux_mode: 'redirect'
into default' popup
The best I can do right now is just to get the email address from the token_id
parameter that Google give in URL after signin. The id_token
field from the URL is a jwt that can be decoded
http://localhost:3006/login#scope=email%20profile%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20openid&id_token=xxxxxxxxx&client_id=xxxxxxxxxxxx-xxxxxx.apps.googleusercontent.com
So How to get the user's profile information with ux_mode
set to redirect
?
from How to get Profile info from Google Signin with redirect mode (no-popup)?
No comments:
Post a Comment