Google Sign In For Web Migration to Google Identity Services - javascript

I have a single page web application that uses Google Sign-In for Web that is being deprecated. I have followed the migration guide and logging in works as expected.
However, when the app restarts I used to run the following code:
auth2.currentUser.get().reloadAuthResponse().then(function (authResponse) {
// User still logged into Google
// Update using authResponse.id_token
}, function (data) {
// Handle user logged out of Google
});
In the reference section of the migration guide it says for GoogleUser.reloadAuthResponse() the action is to "Remove. An ID token has replaced OAuth2 access tokens and scopes.".
I've looked through the documentation and I haven't seen a way to check if the user is still logged in that is similar to reloadAuthResponse. What way should I replace this?

Related

Why is Sign in With Google example code returning the wrong token to login to Firebase?

Working on a Firebase app that will help manage a users Google Calendar.
I am using the official Google Calendar Quickstart Guide code - https://developers.google.com/calendar/api/quickstart/js
Everything works great, I can sign in, authorize access and pull the calendar events.
Firebase allows you to log a user in by passing Firebase a Google ID token.
On this official Firebase guide, https://firebase.google.com/docs/auth/web/google-signin#expandable-2 it shows how to use the Sign In With Google library and then pass the resulting ID token to Firebase to sign in.
Everything works fine on the provided Firebase code until it get to this line.
const idToken = response.credential;
The token returned to the Google Sign In callback doesn't include a credential.
The object has these properties:
access_token, expires_in, scope, token_type
So when I try to access the .credential on the response it is undefined, so the resulting call to login to Firebase with that credential fails.
The new Sign In With Google flow separates the authentication and authorization. https://developers.google.com/identity/gsi/web/guides/overview#separated_authentication_and_authorization_moments and states
"To enforce this separation, the authentication API can only return ID
tokens which are used to sign in to your website, whereas the
authorization API can only return code or access tokens which are used
only for data access but not sign-in."
Something seems strange because it appears the token being returned is the Google Calendar data access token, when I thought it would be the Google Sign in token.
I've googled every combination, and read any related SO answer I can think of trying to fix this, seems like I am missing something simple.
Figure out it was the wrong token, because when I removed everything out and just tried to implement a basic Sign In With Google, that token works.
Used the Google provided button/popup that their library provides from their guide here:
<div id="g_id_onload"
data-client_id="CLIENT_ID_GOES_HERE"
data-callback="handleCredentialResponse">
</div>
In the handleCredentialResponse callback, the returned token did have a .credential
Passing that to Firebase worked to login.
const idToken = response.credential;
const provider = new firebase.auth.GoogleAuthProvider();
const credential = provider.credential(idToken);
auth.signInWithCredential(credential).catch((error) => {
// Handle Errors here.
});
So obviously I wasn't understanding what was happening in the Google Quick start example.
Now I assume I can use the Google Sign In Token to request Calendar OAuth permissions.

Why does a Cloud Function for Firebase (deployed without errors), throw "Uncaught (in promise) FirebaseError: internal" when called? [duplicate]

After months of developing a Web App under Firebase suddenly these days we have a problem with the Authentication, it returns this console.alert only with Facebook and google login (email/pass login works fine):
[firebase-auth] Info: The current domain is not authorized for OAuth
operations. This will prevent signInWithPopup, signInWithRedirect,
linkWithPopup and linkWithRedirect from working. Add your domain
(front.qualify.mx) to the OAuth redirect domains list in the Firebase
console -> Auth section -> Sign in method tab.
The App uses 3 different sub-domains, and in all 3 we can access over email/pass but not Facebook nor google.
We tried updating the Firebase initialization script, nothing. We have checked the API keys (in the Google APIs Credentials) and there was a new "Server key (auto created by Google Service)" which no one told us it was generated (Jan. 18th), so we edited it to include the domains as the original API key in different ways (w/wo * and /*), nothing. We deleted this new Server Key, suddenly something different, now the console includes a 403 error before the alert stated above and returns auth/timeout code inside the object.
We also found the Identity Toolkit API has detected many errors, so we tried to add the URLs for login, logout and email, but nothing happens when trying to save.
What are we missing?
The solution was adding my-app.firebaseapp.com (being my-app the unique identifier of our Firebase App) to the HTTP referrers in the Browser-Key Credentials from the Google APIs console and wait some time to propagate.
After many months of development the app never had a problem, and we are sure we never removed such referrer (if it was ever there).
Anyway... it's done and learned.
The simple way I was able to solve this issue I had with my ionic project was by following the instructions in the log, if you don't see any message try console log the response from firebase.
So what I simply did was follow the url: https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project='projectId'
*projectId = the Id of your project
and enable the Identity API something it brought up. Finish, and it worked instantly.

Single flow: sign user in via Google oAuth AND grant offline/server access?

I'm trying to implement Google sign-in and API access for a web app with a Node.js back end. Google's docs provide two options using a combo of platform.js client-side and google-auth-library server-side:
Google Sign-In with back-end auth, via which users can log into my app using their Google account. (auth2.signIn() on the client and verifyIdToken() on the server.)
Google Sign-in for server-side apps, via which I can authorize the server to connect to Google directly on behalf of my users. (auth2.grantOfflineAccess() on the client, which returns a code I can pass to getToken() on the server.)
I need both: I want to authenticate users via Google sign-in; and, I want to set up server auth so it can also work on behalf of the user.
I can't figure out how to do this with a single authentication flow. The closest I can get is to do the two in sequence: authenticate the user first with signIn(), and then (as needed), do a second pass via grantOfflineAccess(). This is problematic:
The user now has to go through two authentications back to back, which is awkward and makes it look like there's something broken with my app.
In order to avoid running afoul of popup blockers, I can't give them those two flows on top of each other; I have to do the first authentication, then supply a button to start the second authentication. This is super-awkward because now I have to explain why the first one wasn't enough.
Ideally there's some variant of signIn() that adds the offline access into the initial authentication flow and returns the code along with the usual tokens, but I'm not seeing anything. Help?
(Edit: Some advice I received elsewhere is to implement only flow #2, then use a secure cookie store some sort of user identifier that I check against the user account with each request. I can see that this would work functionally, but it basically means I'm rolling my own login system, which would seem to increase the chance I introduce bugs in a critical system.)
To add an API to an existing Google Sign-In integration the best option is to implement incremental authorization. For this, you need to use both google-auth-library and googleapis, so that users can have this workflow:
Authenticate with Google Sign-In.
Authorize your application to use their information to integrate it with a Google API. For instance, Google Calendar. 
For this, your client-side JavaScript for authentication might require some changes to request
offline access:
$('#signinButton').click(function() {
auth2.grantOfflineAccess().then(signInCallback);
});
In the response, you will have a JSON object with an authorization code:
{"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}
After this, you can use the one-time code to exchange it for an access token and refresh token.
Here are some workflow details:
The code is your one-time code that your server can exchange for its own access token and refresh token. You can only obtain a refresh token after the user has been presented an authorization dialog requesting offline access. If you've specified the select-account prompt in the OfflineAccessOptions [...], you must store the refresh token that you retrieve for later use because subsequent exchanges will return null for the refresh token
Therefore, you should use google-auth-library to complete this workflow in the back-end. For this,
you'll use the authentication code to get a refresh token. However, as this is an offline workflow,
you also need to verify the integrity of the provided code as the documentation explains:
If you use Google Sign-In with an app or site that communicates with a backend server, you might need to identify the currently signed-in user on the server. To do so securely, after a user successfully signs in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity of the ID token and use the user information contained in the token
The final function to get the refresh token that you should persist in your database might look like
this:
const { OAuth2Client } = require('google-auth-library');
/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow. Return the refresh token.
*/
function getRefreshToken(code, scope) {
return new Promise((resolve, reject) => {
// Create an oAuth client to authorize the API call. Secrets should be
// downloaded from the Google Developers Console.
const oAuth2Client = new OAuth2Client(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// Generate the url that will be used for the consent dialog.
await oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope,
});
// Verify the integrity of the idToken through the authentication
// code and use the user information contained in the token
const { tokens } = await client.getToken(code);
const ticket = await client.verifyIdToken({
idToken: tokens.id_token!,
audience: keys.web.client_secret,
});
idInfo = ticket.getPayload();
return tokens.refresh_token;
})
}
At this point, we've refactored the authentication workflow to support Google APIs. However, you haven't asked the user to authorize it yet. Since you also need to grant offline access, you should request additional permissions through your client-side application. Keep in mind that you already need an active session.
const googleOauth = gapi.auth2.getAuthInstance();
const newScope = "https://www.googleapis.com/auth/calendar"
googleOauth = auth2.currentUser.get();
googleOauth.grantOfflineAccess({ scope: newScope }).then(
function(success){
console.log(JSON.stringify({ message: "success", value: success }));
},
function(fail){
alert(JSON.stringify({message: "fail", value: fail}));
});
You're done with the front-end changes and you're only missing one step. To create a Google API's client in the back-end with the googleapis library, you need to use the refresh token from the previous step.
For a complete workflow with a Node.js back-end, you might find my gist helpful.
While authentication (sign in), you need to add "offline" access type (by default online) , so you will get a refresh token which you can use to get access token later without further user consent/authentication. You don't need to grant offline later, but only during signing in by adding the offline access_type. I don't know about platform.js but used "passport" npm module . I have also used "googleapis" npm module/library, this is official by Google.
https://developers.google.com/identity/protocols/oauth2/web-server
https://github.com/googleapis/google-api-nodejs-client
Check this:
https://github.com/googleapis/google-api-nodejs-client#generating-an-authentication-url
EDIT: You have a server side & you need to work on behalf of the user. You also want to use Google for signing in. You just need #2 Google Sign-in for server-side apps , why are you considering both #1 & #2 options.
I can think of #2 as the proper way based on your requirements. If you just want to signin, use basic scope such as email & profile (openid connect) to identify the user. And if you want user delegated permission (such as you want to automatically create an event in users calendar), just add the offline access_type during sign in. You can use only signing in for registered users & offline_access for new users.
Above is a single authentication flow.

Meteor.user is null after (apparently) successful login

I have a simple Meteor js app that allows you to create a user account and log in, or to log in with your existing Google account via oauth (thanks to the accounts-google package).
When using the app, I enter my username and password, everything works fine. However, when I click "Sign in with Google", the google oauth pop-up asks me to select which google account I want to use for this login. I select the account, the pop up waits a second, closes, and then nothing happens. No pop-ups being blocked, no "failed login" messages. It's as if nothing happened at all.
I'm certain that the user is never being defined when I use oauth login because Meteor.user() gives me null in the JS console.
What could be going on here? Or how would I debug this? Suggestions appreciated.
p.s. If any additional information is needed, I can ammend.
You probably messed up oauth configuration either on the Meteor side or Google Developers Console side, so here is a quick recap.
Google Developers Console :
Under APIs & auth > Credentials, create a new Client ID in the OAuth section.
Choose Web Application and specify both correct redirect URIs and JavaScript origins :
REDIRECT URIS
http://localhost:3000/_oauth/google?close
http://your-production-domain.com/_oauth/google?close
JAVASCRIPT ORIGINS
http://localhost:3000
http://your-production-domain.com
Meteor configuration :
Be sure to add these packages :
meteor add accounts-google
meteor add service-configuration
In server/config.js, add these lines from http://docs.meteor.com/#meteor_loginwithexternalservice
ServiceConfiguration.configurations.remove({
service: "google"
});
ServiceConfiguration.configurations.insert({
service: "google",
clientId: "????????????????.apps.googleusercontent.com",
secret: "????????????????"
});
The clientId and secret fields should be set to those in the Google Developers Console.
Then call Meteor.loginWithGoogle() in the click handler of your login form and it should work as expected.

Adding a test user in graph api (javascript sdk)

I am trying to add a couple to test users to an app I'm developing using google app engine and the javascript sdk. Following this link:, I tried this code:
FB.api ('/app_id/accounts/test-users', 'post', {installed:'true', permissions:'read_stream'}, function (response) {
alert (response.id);
});
(app_id was changed to the App ID as obtained in http://www.facebook.com/developers/apps.php)
But I get a popup "undefined". What is wrong with this code? I could not find any example for the javascript sdk.
As per the same facebook help page, response is supposed to be:
{
"id": "1231....",
"access_token":"1223134..." ,
"login_url":"https://www.facebook.com/platform/test_account.."
}
BTW, if I log in as myself,
FB.api('/me', function(user) {
welcomeMsg (user);
});
works just fine, so it's not a problem with app activation.
I don't think it's possible to perform this type of task using the Javascript SDK, which is intended to make calls on behalf of a user, not an app. For this type of call, it's necessary to authenticate as the app, and for that you need the app OAuth token and secret, which aren't available via Javascript (nor should they be, for security reasons). So the best solution here is to make this call serverside. To do so, you should follow the "App Login" instructions here to get an app access token, and then pass that token in to the /app_id/accounts/test-users API call (as the "access_token" param)

Categories

Resources