Meteor.user is null after (apparently) successful login - javascript

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.

Related

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.

Nightwatch Google OAuth2 token

I am running a UI test on the webpage that uses google oauth2 for login (Gmail address as username). My problem is that I need to login with multiple different users during the same test, but after the first logout, pressing login again automatically logs in the previous user. Does not happen when I manually try to login/logout.
I'm assuming this is because during test run auth token is still active and google logs in automatically.
Things I have tried so far:
1) - importing google-auth-library and run GoogleAuth.disconnect() -> returns error: disconnect is not a function.
2) - How to reset google oauth 2.0 authorization? - import 'googleapis' and run gapi.auth.setToken(null) - gapi.auth has no such option.
Can't try revokeAccess functions suggested since I don't know the token value.
Is there a way for me to retrieve login token from my test (I'm guessing it would be from client side) so that I could set it to null/delete it?

Facebook app and session handling

What is the way to do the app logout when the user is logged out from Facebook?
Let's consider the following situation: I've got the app that build into the webshops, so I somehow need to know the login status of the user. When the user logs into facebook and then into my app, he can 'save' or 'bookmark' the page. There's an option - to provide the logout button which logs out from the app, and then from facebook.
But my problem is the opposite: how to detect if the user has logged out from facebook - inside my app, which is built into the webshop? There's no way to detect it from the backend, only the js. Can I somehow build in the facebook login status change into my js code so it will do the check right away when my js snippet has loaded on a website?
You can make a simple graph api request like
https://graph.facebook.com/me/?access_token={your%20access%20token}
If user is logged in then you will receive a response with user information otherwise you will get a response as follows
{
"error": {
"message": "Error validating access token: This may be because the user logged out or may be due to a system error.",
"type": "OAuthException",
"code": 190,
"error_subcode": 467
}
}
Using this you can differentiate whether is user is logged in into fb or not.
Thanks,
Pranav
Could not find any reasonable solution, so did the following:
every request is directed to the app
on the app landing page Facebook JS SDK checks the login status and handles everything

Can't login to Instagram using Client-Side (Implicit) Authentication

I'm trying to build a client-side application that allows people to login with their Instagram accounts. Problem is, I'm not sure if that's still possible.
I've coded a sample JavaScript after reading "Client-Side (Implicit) Authentication" section of their related docs.
I'm getting the following error:
{
"code": 400,
"error_type": "OAuthException",
"error_message": "JS login temporarily disabled"
}
From the error message I'm guessing it's not about my code but it's something on Instagram's side. Is there a way for me to do client-side login? Also, if I can't, what are my options?
Thanks.
I had similar issue and this is how I fixed it.
You have to uncheck the "Disable implicit OAuth:" by going to :
-> Manage Clients
-> Click edit on the app/webapp.
-> Uncheck - Disable implicit OAuth:
-> Update the settings and try to run it again by going to the link :
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
In the link, replace the values that were provided to you and in the response_type, give value as token to get the access token and if you want to get the request code, just replace token with the code in the URL.
Hope this helps for you and for future viewers.. Good luck.. :)
Just unset the "Disable implicit OAuth:" in app settings.
So, it seems it's impossible to do JS login at the moment with Instagram.
But they still allow implicit redirects so the solution is to have a server to make a redirect to your client side application. You only need two endpoints. I've written a small Node.JS app for this which you can find here.
I had tried for the same,I think there are not still providing any api to login with Instagram credentials username and password,You can just authenticate your account via
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

How get Facebook token using Oauth2 with chrome.identity

I'm using chrome.identity in a packaged app to get a user token using Facebook. I call chrome.identity.launchWebAuthFlow, and I need to take the access token, send it to the server, and then access token is used to verify the user.
Works great with Google+. But for some reason, it doesn't work for Facebook. For some reason, Facebook's OAuth appears to be special. I've added the extensionid.chromiumapp.org to the list of redirect URLs in the API. Added
"https://extensionid.chromiumapp.org/*",
"https://facebook.com/*",
"https://www.facebook.com/dialog/",
"https://graph.facebook.com/*"
to manifest.json. But nothing changed.
In calling chrome.identity.launchWebAuthFlow I use URL like this
"https://www.facebook.com/dialog/oauth/access_token?" +
"client_id=myclientid&client_secret=myclientsecret&" +
"response_type=token&grant_type=client_credentials"
When I try to invoke it, I get the following error message:
«launchWebAuthFlow completed Object {message: "Authorization page could not be loaded."} »
And when I use URL like
«"https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=https://myextensionid.chromiumapp.org/facebook.com=token&scope=user"»
I get the next error:
«launchWebAuthFlow completed Object {message: "User interaction required."} undefined »
I try to get facebook token in 4 days. I am tired. What I do wrong?
Why chrome.identity.getAuthToken work great for Google+ and chrome.identity.launchWebAuthFlow dont with Facebook?
I hope someone have done the same things and can help me.
I have solved the problem. Here is an example https://github.com/blackgirl/Facebook_Oauth2_sample_for_extensions
The "User interaction required." message means that the user needs to sign in to Facebook, and/or approve the requested OAuth scopes. The setting the { interactive: true } flag would allow identity.launchWebAuthFlow to display a window where the user would perform these steps. Since you are passing the { interactive: false } flag, identity.lauchWebAuthFlow fails.
https://www.facebook.com/dialog/oauth is most likely the URL you want to use to start your flow. The client_credentials grants are normally for cases where you are accessing resources owned by your app, rather than resources owned by a specific user.
However if you did want to debug that "Authorization page could not be loaded" case, the way to do it would be to open up chrome://net-internals and look for error responses coming back from Facebook.
chrome.identity.launchWebAuthFlow(
{'url': 'https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=https://myextensionid.chromiumapp.org/facebook.com=token&scope=user, 'interactive': true},
function(redirect_url) {
/* Extract token from redirect_url */
console.log(redirect_url);
});
//'interactive': true
what will this flag do, will show a dialog box asking username and password
upon successful login it will ask for grant access just press that and
you will receive redirect url in above function body.

Categories

Resources