0

I'm trying to implement the Google oAuth2 API for login to my webapp using google credentials via Spring Social.

The query to Google is as follows

    googleConnectionFactory = new GoogleConnectionFactory(myKey, mySecret);
    oauthOperations = googleConnectionFactory.getOAuthOperations();
    final String redirectUri = "http://localhost/googleCallback";
    final OAuth2Parameters params = new OAuth2Parameters();
    params.setRedirectUri(redirectUri);
    params.setScope("https://www.googleapis.com/auth/userinfo.profile");
    final String authorizeUrl = oauthOperations.buildAuthorizeUrl(
            GrantType.AUTHORIZATION_CODE, params);
    response.sendRedirect(authorizeUrl);

Once requested, I am taken to the Google login page. The URL shows scope=https://www.googleapis.com/auth/userinfo.profile

Once logged in, the user is redirected back to my webapp and the method below is called

    final String callbackUrl = "http://localhost/googleCallback";
    final AccessGrant accessGrant = oauthOperations.exchangeForAccess(code,
            callbackUrl, null);
    // THIS CRASHES WITH 401
    final Connection<Google> connection = googleConnectionFactory
            .createConnection(accessGrant);
    // THIS CRASHES TOO WITH 401
    new GoogleTemplate(accessGrant.getAccessToken()).userOperations().getUserProfile();

Am I missing something?

Simo L.
  • 321
  • 1
  • 3
  • 20

1 Answers1

3

I had to manually concatenate the access token to the API url in order to get it to work. Apparently Spring Social doesn't set the Access Token while sending the query...

LegacyGoogleProfile profile = new GoogleTemplate(
accessGrant.getAccessToken()).getRestTemplate().getForObject(
"https://www.googleapis.com/oauth2/v2/userinfo?access_token="
                    + accessGrant.getAccessToken(),
LegacyGoogleProfile.class);
Simo L.
  • 321
  • 1
  • 3
  • 20
  • It's somewhat better practice (more secure) to send the access token as an HTTP header (Authorization: Bearer ). Reason is that jamming it into the URL means that it likely gets logged on the server side. – Tim Bray Feb 05 '13 at 16:00
  • I agree. This was a workaround. I really don't know why `googleConnectionFactory.createConnection(accessGrant);` would crash though while they both have the same (and correct) access token.. – Simo L. Feb 05 '13 at 16:31
  • 1
    Just to be clear, the issue you're having is with Spring Social Google, not with Spring Social itself. Spring Social Google is a community-led project, led by Gabriel Axel. I'm sure that Gabriel would appreciate knowing about this problem. May I suggest that you submit an issue or (better yet) a pull request to his project at https://github.com/GabiAxel/spring-social-google. – Craig Walls Feb 11 '13 at 15:15