I am integrating google sign-in in my web app. I followed the instructions from here. But I am unable to get any user information from the sign-in. The sign-in button works perfectly fine though.
<meta name="google-signin-client_id" content="3*****-c*******************.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-signin2 googleSignIn" data-onsuccess="onSignIn"></div>
I use these javascript functions:
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());
email=profile.getEmail();
}
}
This function results in an error: auth2 is not defined.
If I use window.onLoadCallback = function() before the function then it gives no error but also nothing in the log. If I use only this instead:
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
console.log("done");
}
again I get no error but also nothing in the console log.
Place this code before if (auth2.isSignedIn.get()) it. Try to run it.
gapi.load('auth2', function () {
auth2 = gapi.auth2.init();
// Sign the user in, and then retrieve their ID.
auth2.signIn().then(function () {
console.log(auth2.currentUser.get().getId());
});
});
Related
After playing around with google sign https://developers.google.com/identity/sign-in/web/sign-in. I wanted to clean up the code a bit by placing it in another file and maybe renaming them.
But somehow data-onsuccess would not work if I put the onSignIn function as an object's attribute.
I have something like this to give it a try
const google_auth = {};
google_auth.id_token = null;
google_auth.onSignIn = (googleUser) => {
const profile = googleUser.getBasicProfile();
const id_token = google_auth.id_token = googleUser.getAuthResponse().id_token;
console.log(profile, 'profile');
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('ID token: ' + id_token);
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.
console.log(id_token.split('.'), 'id_token split');
};
then for html I tried
<div class="g-signin2" data-onsuccess="google_auth.onSignIn"></div>
the function will not be called though. If I just use the original code such as
const google_auth = {};
google_auth.id_token = null;
function onSignIn(googleUser) {
const profile = googleUser.getBasicProfile();
const id_token = google_auth.id_token = googleUser.getAuthResponse().id_token;
console.log(profile, 'profile');
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('ID token: ' + id_token);
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.
console.log(id_token.split('.'), 'id_token split');
};
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Which works perfectly, I tried googling about data-onsuccess attributes but no one really talk much about this situation. Most people saying it doesn't work with the framework.
Thanks in advance for any help / suggestions.
This is the HTML:
<div id="button_google_login" class="customGPlusSignIn" onclick="startApp();">
<span class="dont_close" style="padding-left: 12px;">Sign In with Google</span>
</div>
JavaScript:
var googleUser = {};
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: '[Secret].apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('button_google_login'));
});
};
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(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.
}, function(error) {
// error or break up
});
}
I need to click the button twice to start the Sign In process, what could be the problem? I also tried the normal non custom version and it worked how it should.
Thanks in advance!
I guess you copied the example from Google Documentation. There the startApp() function is called at the end of the body Tag. Therefore the click handler to the Google button is assigned, when the document has loaded. You changed the behaviour insofar as that the click handler is only assigned, when somebody clicks the button. Because of that, you have to click that button two times.
Why don't you want to do it like in the Google provided example?
Simply add <script>startApp();</script> before the closing </body> Tag and remove the onclick="startApp(); attribute from your button.
I would to a onClick event on a btn and then call a login function
function login() {
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.
}
Try to get the user's token I got:
Uncaught TypeError: profile.getAuthResponse is not a function
Where
profile = googleUser
This is my code:
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.
console.log('Token id: ' + profile.getAuthResponse().id_token);
}
Nothing really special there.
I read on google doc that I should use the function getAuthResponse().id_token and not GoogleUser.getId() for security purposes.
In this question: Google access_token is undefined
Here Sharkos suggest to use gapi.auth.getToken().access_token but I got null
Any ideas why I got that error?
Try this
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.
console.log('Token id: ' + googleUser.getAuthResponse().id_token);
}
You set var profile = googleUser.getBasicProfile(); Therefore, you can't use getAuthResponse() on getBasicProfile(). it has to be googleUser.getAuthResponse()
https://developers.google.com/identity/sign-in/web/reference#googleusergetauthresponseincludeauthorizationdata
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am trying to integrate the google signing button onto my web application. Its my first time doing it, and I keep getting the following message in my console log...
auth2 is not defined
Also when I refresh the page the google button says "Sign In" instead of "Signed In"
Below is my code. Thanks!
<script>
gapi.load('auth2', function () {
auth2 = gapi.auth2.init();
// Sign the user in, and then retrieve their ID.
auth2.signIn().then(function () {
console.log(auth2.currentUser.get().getId());
});
});
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());
}
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!
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());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
}
</script>
Don't let Google API mislead you. The error is probably because of this line (and the code being in ('strict mode'):
auth2 = gapi.auth2.init();
as the error states that "auth2" is not defined (and you are not allowed to create variables in the global space while in strict mode). Declare it like:
var auth2 = gapi.auth2.init();
Same thing happening here gapi auth2 init failing with "Uncaught ReferenceError: auth2 is not defined".
I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user's login in status with my app key or something similar?
I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google's tutorial listed above):
<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
alert(profile.getName());
}
function logout()
{
alert('logging out');
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
...
</head>
Code In Body (1st line from Google's tutorial listed above, 2nd line to trigger logout test)
<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.
Load the JavaScript library, make sure you are not deferring the load :
<script src="https://apis.google.com/js/platform.js"></script>
Then initialize the library and check if the user is logged in or not
var auth2;
var googleUser; // The current user
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'your-app-id.apps.googleusercontent.com'
});
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
auth2.isSignedIn.listen(signinChanged);
auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
};
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
// Redirect somewhere
};
var onFailure = function(error) {
console.log(error);
};
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
var userChanged = function (user) {
if(user.getId()){
// Do something here
}
};
Don't forget to change the app id
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var myUserEntity = {};
myUserEntity.Id = profile.getId();
myUserEntity.Name = profile.getName();
//Store the entity object in sessionStorage where it will be accessible from all pages of your site.
sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
alert(profile.getName());
}
function checkIfLoggedIn()
{
if(sessionStorage.getItem('myUserEntity') == null){
//Redirect to login page, no user entity available in sessionStorage
window.location.href='Login.html';
} else {
//User already logged in
var userEntity = {};
userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
...
DoWhatever();
}
}
function logout()
{
//Don't forget to clear sessionStorage when user logs out
sessionStorage.clear();
}
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.
To check is user Signed-in use:
gapi.auth2.getAuthInstance().isSignedIn.get()
Adding on to Joseph's answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().
if (auth2.isSignedIn.get()) {
googleUserProfile = auth2.currentUser.get().getBasicProfile()
console.log('ID: ' + googleUserProfile.getId());
console.log('Full Name: ' + googleUserProfile.getName());
console.log('Given Name: ' + googleUserProfile.getGivenName());
console.log('Family Name: ' + googleUserProfile.getFamilyName());
console.log('Image URL: ' + googleUserProfile.getImageUrl());
console.log('Email: ' + googleUserProfile.getEmail());
}
From the docs: https://developers.google.com/identity/sign-in/web/people
according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) -
google stopped supporting the Sign-In Javascript web auth API:
We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.