Google+ signin button - unable to make authenticated calls - google-plus

I am adding the new Google+ signin button to my app and having some problems with making authenticated calls. I have included the html and javascript as described in the docs and the signin works. I have can even see the access token. However when I make a request to an authenticated endpoint I get an "invalid credentials" response. For example I am attempting:
gapi.client.oauth2.userinfo.get().execute(function(resp){console.log(resp);});
I can make this call if I use the regular google oauth methods ( gapi.auth.authorize()).
What is going on here? what am I doing wrong?
I am requesting the userinfo.email and userinfo.profile scopes with the google+ button.
Html for G+ signin:
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-apppackagename="com.mypackage"
data-clientid="myclientID"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/devstorage.read_only https://www.googleapis.com/auth/plus.login">
js included for G+ signin button(just before ):
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
callback for G+ button:
function signinCallback(authResult) {
if (authResult['access_token']) {
signin();
} else if (authResult['error']) {
console.log('There was an error: ' + authResult['error']);
}
}
Request for userprofile:
gapi.client.oauth2.userinfo.get().execute(function(resp) {console.log(resp);});
The request includes the Authorization header with a token(seen through chrome dev tools).
Update:
I have also attempted using gapi.auth.authorize() in immediate mode. This did not work for and returned a null response. When I ran this with immediate mode set to false, I was presented with the authorization prompt (again, after authorizing with g+ button). After this my authorized calls worked. Below is my code:
gapi.auth.authorize({client_id: 'myClientID', scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/devstorage.read_only',
immediate: mode, response_type: 'token id_token'}, callback);

I built a repro of your use case and documented it in this gist, it's working fine for me. Some other notes:
if you request plus.login, you shouldn't request userinfo.profile because it's included as part of plus.login and would create duplicate permissions in the authorization dialog. You can find more on this in the best practices section of the docs.
you should use
data-apppackagename only to provide the package for a valid android application, otherwise you might trigger 500 errors in the auth dialog.

The first thing to check is to make sure you're requesting the scopes that gapi.client.oauth2.userinfo is looking for. You can request additional scopes as part of the button.
Use the network console in something like Chrome to see if there is an Authorized: header passed along with the request and what it might be. If it isn't sent or is undefined, the token itself may not have been set, in which case you might need to set the auth token with gapi.auth.setToken() as documented at https://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs or just call gapi.auth.authorize in immediate mode with the same scopes, which should make sure it gets the token.

I have done the google authentication by using OAuth2Authenticator in android xamarin. steps might be helpful to you.
1.register in google developer console as webapplication instead of installed application(android)* provide the redirect url with valid url ("http://abcd.com/xyz.aspx") same should be used in the application code.
2.on authentication complete it will return access_token
3.by using the access_token make the REST request to get user complete information (https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessTokenValue + “.)
4.Deserialize the json response to get information in object.
check more here :Google Account login Integration for android Xamarin

Related

Auth0 JWT as access token comes in only on second login

I have this issue and I'm not sure whether it is a "bug" or my fault somewhere.
All of this is for a SAP on ASP.NET Core Angular which is accessing Auth0 on a hosted page.
I have updated my hosted page Auth0lock object on the hosted page to inculde a params object with a specified audience
var lock = new Auth0Lock(config.clientID, config.auth0Domain, {
auth: {
redirectUrl: config.callbackURL,
responseType: 'token',
params: {
"audience": "https://api.webatom.com"
}
},
assetsUrl: config.assetsUrl,
allowedConnections: connection ? [connection] : null,
rememberLastLogin: !prompt,
language: language,
languageDictionary: languageDictionary,
theme: {
//logo: 'YOUR LOGO HERE',
//primaryColor: 'green'
},
prefill: loginHint ? { email: loginHint, username: loginHint } : null,
closable: false,
// uncomment if you want small buttons for social providers
// socialButtonStyle: 'small'
});
During the first login I get the usual auth result where I receive the JWT as the id_token and a short string for the access token and I don't get a message in auth0 about account access request.
During the second and other logins I get what I want. I get the message and I get the JWT as access token and id_token as null.
How do I get that second result from the start, right from the first login? Is that a bug or am I doing something wrong?
Thank you.
PS: I don't have any rules or hooks implemented at that moment.
As a first step: Add https://jwt.io as an allowed callback to your Client, revert the Auth0 Hosted Login page back to its default (ie. remove the changes you made), then modify the url below with your own settings, and paste it into a browser URL and hit return.
https://{{YOUR_TENANT}}.auth0.com/login?client={{YOUR_CLIENT_ID}}&redirectUrl=https://jwt.io&responseType=token&connection={{YOUR_CONNECTION_NAME}}&audience=https://api.webatom.com&scope=openid
All going well, it should return a JWT Access Token and auto-populate that into the JWT.io text-area.
Next, try this - using Auth0's authorize URL instead. Again, use Auth0 default hosted login page, not the one you modified.
https://{{YOUR_TENANT}}.auth0.com/authorize?client_id={{YOUR_CLIENT_ID}}&protocol=oauth2&redirect_uri=https://jwt.io&response_type=token&scope=openid profile&audience=https://api.webatom.com&nonce=123&state=xyz
Should be same result. And presumably this is what you want every time?
If you do want an Id Token, then simply modify responseType / response_type to be token id_token.
So I would recommend you do not modify the Auth0 Hosted Login page settings for Lock directly (authentication related params..), but instead just send through the parameters you want with the request as per the /authorize endpoint above. If you have a Client application using auth0.js for example, you can set everything up at the Client and send it through when the user authenticates.
Sample snippet for auth0.js library config might be:
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientId,
redirectUri: AUTH_CONFIG.callbackUrl,
audience: "https://webapi.com",
responseType: 'token id_token', // just use token if you don't need id token
scope: 'openid profile read:book' // read:book is a scope defined for API
});
So far I have found an interesting work around...
When an opaque token is returned, you can simply copy its aud hash and paste it into the Audience parameter when creating the JwtBearerOptions object into the startup class.
That fixes the error with the invalid audience when using the [Authorize] annotation in the controller api which was the main reason why I needed the jwt from the start.
I thought the only way to get the audience insde the jwt for the JwtBearer to decode it correctly was to set the audience in on the hosted page so it would be returned with the JWT inside the access token.

Signing out using Google API not working

I followed the instructions in:
https://developers.google.com/identity/sign-in/web/sign-in
Everything works (signing in a user) but I cannot sign out a user. I get the following error :
Uncaught gapi.auth2.ExternallyVisibleError: gapi.auth2 has been
initialized with different options
It fails when executing :
auth2 = gapi.auth2.init();
(https://developers.google.com/identity/sign-in/web/sign-in#sign_out_a_user)
I need code examples to sign out the user from my web application and also to sign the user completely from the Google account.
gapi.auth2.init(); was called before by
<div class="g-signin2">
which uses gapi.auth2. You should call
auth2 = gapi.auth2.getAuthInstance();
instead of gapi.auth2.init(). Full example:
Sign out
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
I encountered the same problem.
If you set it up according to these instructions you can sign out a user by calling
gapi.auth.signOut();
You should run this code from web server (ex: Apache, Node.js). The Google Sign In API not working if you directly access files (ex: index.html)

Accessing Shoeboxed API with Google Apps Script (OAuth v2)

I'm trying to initiate a session with the Shoeboxed API via Google Apps Script. I hoped I could use Apps Script internal library to access it but I'm having issues. Here is my attempt:
function testAPI() {
var consumerKey = '';
var consumerSecret = '';
var oauthConfig = UrlFetchApp.addOAuthService('shoeboxed');
oauthConfig.setAccessTokenUrl(
'https://id.shoeboxed.com/oauth/token');
oauthConfig.setRequestTokenUrl(
'https://id.shoeboxed.com/oauth/token');
oauthConfig.setAuthorizationUrl(
'https://id.shoeboxed.com/oauth/authorize');
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);
var options = {
'oAuthServiceName' : 'shoeboxed',
'oAuthUseToken' : 'always'
};
var url = 'https://api.shoeboxed.com/v2/user';
var response = UrlFetchApp.fetch(url, options);
Logger.log("Response: " + response.getContentText());
}
It's failing at the point where it attempts to fetch user data via the API url with an authorization failed message. I'm not sure what I'm doing wrong. Information about the API and OAuth can be found here: https://github.com/Shoeboxed/api/blob/master/sections/authentication.md
New method:
It looks like that API requires OAuth2, but the UrlFetchApp.addOAuthService method only works with the older version of OAuth.
There's a new method ScriptApp.newStateToken() which can be used in combination with OAuth2, but it requires more manual/explicit control over the OAuth2 steps. It generates a state token.
A minor detail on that method:
Note that when you construct URLs, the state token should passed as a URL parameter on the .../authorize URL, not embedded as a URL parameter within the .../usercallback URL.
For example:
You would want to redirect the user to:
https://id.shoeboxed.com/oauth/authorize?client_id=<your client id>&response_type=code&scope=all&redirect_uri=<your site>&state=<CSRF token>
where redirect_uri is:
https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback
When the user clicked authorize, Shoeboxed should redirect them to:
https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback?state=<CSRF token>
oauth2 support for the shoeboxd API has just been added to the cEzyOauth2 Google Apps Script library.
You can copy the pattern to your app and include the library as described here
It uses the statetoken as described by Steve Lieberman, and takes care of the oauth2 conversation, token handling and refreshing automatically.

How to pass authorization code from JSP to Servlet

I am at my wits end, 7 hours and counting.
I am new to FB development and am having an issue of passing the authorization code from my JSP to my Servlet.
1.) I use the social plugin for login in my JSP as shown below
<fb:login-button>Login with Facebook</fb:login-button>
This logs the user in and allows them to grant my app access to their personal information
2.) Once login and authorization are successful, the user is forwarded to my servlet from the JSP via the code below
FB.Event.subscribe('auth.login', function (response) {
window.location = "testservlet";
});
3.) But when I attempt to get the authorization code (so that I can get the auth. token) in my Servlet, the "code" is empty, see the code I am using to retrieve below
String authCode = req.getParameter("code");
Can anyone tell me what I am doing wrong? I am sure that I am missing something so simple..or am trying to do more than is necessary, thanks in advance
I am not familiar with Facebook dev, but concerning servlets, window.location normally speaking will not take you to a servlet.
try using jquery's ajax function and pass a "code" parameter. Do something like :
$.ajax({
url: yourServletPath+"testservlet",
data:"code="+codevariable,
dataType: "whatever data type your servlet returns",
success: function(response)
{
// wtv code to be done
}
});

Facebook C# SDK: OAuth 2 in Silverlight 4 browser app

I'm completely newbie at authentication proccess with OAuth (I'm trying to make use of OAuth 2, exactly), and the example I am following to authenticate by using Facebook SDK latest release says that this code snippet should work for C# .NET environments (http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx):
webBrowser.Navigate(loginUrl);
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
Since I am programming a browser SL app, the WebBrowser control displays nothing, so I am not either able to catch the response, how could I do something equivalent to that in my app? Or how could I manage to complete the authentication proccess if there is no equivalent way? Thanks!
A suggestion: Why don't you try to parse the WebResponse when you receive it as opposed to listening for the event?
I use Facebook OAuth in my web app. It is nothing but a series of URL posts with the correct parameters.
Take a look at this post: Login using Facebook Problem after logging out (All the details are in the answer and comments)
Here are the brief steps:
Call the Facebook OAuth Dialog URL with your AppId, redirect url, and permissions. Request_type should be "code"
When the user logs in and authorizes you application, they will be redirected to the redirect url with a "code" querystring parameter.
Take the value of the code parameter and make another call to Facebook to get the token.
Use this token to make calls on the user's behalf.