Google oAuth2 API提供了401 UNAUTHORIZED

时间:2013-02-04 15:19:30

标签: java-ee spring-social google-oauth

我尝试通过Spring Social使用Google凭据实施Google oAuth2 API以登录我的网络应用。

对Google的查询如下

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

请求后,我将转到Google登录页面。该网址显示scope=https://www.googleapis.com/auth/userinfo.profile

登录后,用户将被重定向回我的webapp,下面的方法称为

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

我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

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

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