2013-02-04 176 views
0

我试图通过Spring Social使用Google凭据实现Google oAuth2 API以登录到我的webapp。Google oAuth2 API提供401未授权

查询到谷歌是如下

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); 

一旦要求,我被带到了谷歌登录页面。该网址显示scope=https://www.googleapis.com/auth/userinfo.profile

登录后,用户被重定向回我的web应用程序和下面的方法被称为

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(); 

我缺少的东西?

+0

**是由Google填充的** accessGrant.accessToken **? –

+0

是的,它被填充。 –

回答

2

我不得不手动连接访问令牌到API网址才能使其工作。显然,Spring Social在发送查询时没有设置访问令牌...

LegacyGoogleProfile profile = new GoogleTemplate(
accessGrant.getAccessToken()).getRestTemplate().getForObject(
"https://www.googleapis.com/oauth2/v2/userinfo?access_token=" 
        + accessGrant.getAccessToken(), 
LegacyGoogleProfile.class); 
+0

将访问令牌作为HTTP头发送(授权:承载<令牌进入此处>),这是更好的做法(更安全)。原因是,将其阻塞到URL中意味着它很可能在服务器端登录。 –

+0

我同意。这是一个解决方法。我真的不知道为什么'googleConnectionFactory.createConnection(accessGrant);'虽然都具有相同(和正确)的访问令牌,但它会崩溃。 –

+1

只是要清楚,您遇到的问题是使用Spring Social Google ,而不是Spring Social本身。 Spring Social Google是一个由Gabriel Axel领导的社区主导型项目。我确信Gabriel会很高兴知道这个问题。我可以建议你在https://github.com/GabiAxel/spring-social-google上向他的项目提交一个问题或(更好的)pull request。 –