2013-01-23 48 views
0

我正在嘗試Google OAuth.I正在開發在IBM WebSphere Server上運行的Web應用程序。應用程序的框架是SpringMVC。OAuth:發送訪問令牌並獲取用戶數據

我想獲取userinfo.profile。我有成功獲取訪問令牌,並找不到使用此令牌並獲取用戶信息的方法。

我的瀏覽器重定向到這個URL https://www.googleapis.com/oauth2/v2/userinfo?access_token="+access.getAccessToken();但得到錯誤

{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "authError", 
    "message": "Invalid Credentials", 
    "locationType": "header", 
    "location": "Authorization" 
    } 
    ], 
    "code": 401, 
    "message": "Invalid Credentials" 
} 
} 

我使用這個訪問令牌罰款或者我應該送一些其他形式的要求嗎?

我送這樣的請求:

GenericUrl shortenEndpoint = new GenericUrl("https://www.googleapis.com/oauth2/v2/userinfo"); 
HttpRequest request1 = rf.buildGetRequest(shortenEndpoint); 
GoogleHeaders headers = new GoogleHeaders(); 
headers.setContentType("application/json; charset=UTF-8"); 
headers.setAuthorization("OAuth " + accessToken); 
request1.setHeaders(headers); 
HttpResponse shortUrl = request1.execute(); 

給我的訪問令牌在這個網址在瀏覽器

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=****** 

我拿到後

{ 
"issued_to": "*****************", 
"audience": "*****************", 
"scope": "https://www.googleapis.com/auth/urlshortener", 
"expires_in": 3515, 
"access_type": "online" 
} 
+0

如果使用Authorization標頭髮送令牌,它也會失敗嗎? – jphuynh

+0

我沒有嘗試過。你能告訴我任何發送這個頭的例子嗎? –

+0

你能詳細說明你是如何發送http請求的嗎? – jphuynh

回答

5

望着tokeninfo響應,有針對其發出的令牌的範圍和您試圖訪問的API之間的不匹配。您似乎有https://www.googleapis.com/auth/urlshortener範圍的訪問令牌。如果您想要使用userinfo API,您應該獲得https://www.googleapis.com/auth/userinfo.profilehttps://www.googleapis.com/auth/userinfo.email範圍的令牌。

+0

你美麗。什麼挖。如果有選擇不止一次投票,那麼我會這樣做十次。 –

+0

如何使用兩個範圍? –

+0

很棒的發現@vlatko,謝謝。 Imran,對於多個範圍,你必須在你的url中傳遞它們。他們必須由空間劃定界限。示例:'範圍= https://www.googleapis.com/auth/userinfo.email+https:// www.googleapis.com/auth/userinfo.profile' – jphuynh

1

看來,您的授權標題不正確。

嘗試:headers.setAuthorization("OAuth " + accessToken);

+0

更改後,得到同樣的錯誤。 –

+0

好的,你可以檢查你的令牌是否仍然有效?您可以撥打https://www.googleapis.com/oauth2/v1/tokeninfo?access_token ='yourToken'進行檢查。 – jphuynh

+0

它返回一些數據,表示令牌很好,但在應用程序中使用時出錯。爲令牌編輯的問題。 –

相關問題