2013-02-04 177 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。 –