2013-04-09 83 views
2

我在使用Google+ API OAuth2令牌時遇到了一些問題。Google+ api - https://accounts.google.com/o/oauth2/token提供的鍵值爲401錯誤

下面是一個簡單的程序,得到OAuth2用戶訪問令牌:

HttpClient httpclient = new HttpClient(); 
     PostMethod postMethod = new PostMethod("https://accounts.google.com/o/oauth2/token"); 
     NameValuePair[] data = { 
       new NameValuePair("client_id", "API KEY HERE"), 
       new NameValuePair("redirect_uri", "URL HERE"), 
       new NameValuePair("client_secret", "SECRET HERE"), 
       new NameValuePair("code", "CODE HERE"), 
       new NameValuePair("grant_type", "authorization_code") 
     }; 
     postMethod.setRequestBody(data); 
     try { 
      int result = httpclient.executeMethod(postMethod); 
      assertEquals(result, 200); 
      System.out.println("Response body: "); 
      System.out.println(postMethod.getResponseBodyAsString()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

這成功地產生了OAuth2令牌。如:ya29.AHES6ZTZgptKHyZ530MoYVDPaeXvjK5DWQzPqxoNNEL2C7gsQwGfmvfT8Q

然後,我建立了一個簡單的測試程序,它可以測試從令牌調用/人API:

@Test 
    public void testGoogleAPIAuthdRequest() throws Exception { 
     String feedUrl = "https://www.googleapis.com/plus/v1/people/me"; 
     String apiKey = "MY API KEY"; 
     String oauthCode = "OAUTH CODE FROM ABOVE"; 
     String jsonStr = executeGoogleFeed(feedUrl, apiKey, oauthCode).getResponseBodyAsString("UTF-8"); 
    } 

    public Response executeGoogleFeed(String feedURL, String apiKey, String oauthCode) throws Exception { 
     StringBuilder urlStr = new StringBuilder(); 
     urlStr.append(feedURL); 
     urlStr.append("?key="); 
     urlStr.append(apiKey); 
     Map<String, String> hashMap = new HashMap<String, String>(); 
     hashMap.put("Authorization", "Bearer " + oauthCode); 
     return HttpUtil.doHttpRequest(urlStr.toString(), MethodType.GET.toString(), null, 
       hashMap); 
    } 

這給了我一個401錯誤。沒有權限。

當我去​​時,令牌顯示爲有效。

另外,當我轉到https://developers.google.com/+/api/latest/people/get並從OAuth2登錄功能獲取OAuth令牌時...我將該OAuth令牌插入到我的JUnit測試中......它的工作原理!

任何人都知道爲什麼我的電話https://accounts.google.com/o/oauth2/token不能用作Google + api中的承載參數?

回答

1

聽起來像是底層的問題是,當您發送用戶進行身份驗證和授權您的應用程序時,您並未請求plus.me範圍。這是在你在這裏顯示之前的步驟完成的,並且是返回上面添加的OAuth2「代碼」的組件。您可能想要更新您的示例以說明如何獲取代碼以及您使用何種範圍來執行此操作。

如果您正確設置範圍,並且您使用的是返回的代碼,則可能是您不斷重複使用相同的代碼。從第一階段返回的OAuth2代碼只能使用一次,發佈後必須很快使用。它被交換爲具有有限生命週期的access_token(這正是您正確嘗試執行的操作)以及具有無限生命週期並用於生成新的access_tokens的refresh_token。

請參閱https://developers.google.com/accounts/docs/OAuth2WebServer瞭解有關用於獲取和交換OAuth2代碼的多步驟過程的完整詳細信息。

+1

我正要來回答我自己的問題。我實際上有錯誤的範圍,因爲谷歌文件有點神祕。好東西謝謝。 – 2013-04-09 16:04:46

+2

請注意,如果您使用的是plus.login作用域,則不需要plus.me作用域。 – Joanna 2013-04-10 00:33:54