2012-11-27 54 views
1

夥計們,如何通過Google OAuth使用資源所有者密碼憑證?

我要找使用com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant的功能例如,驗證用戶不使用基於Web的用戶界面。嘗試了班級中提供的樣本(將https://server.example.com/authorize替換爲https://accounts.google.com/o/oauth2/auth),但獲得了invalid_request響應。這是發佈到的正確網址嗎?請求是否需要設置其他屬性?試過這樣的設置範圍,但沒有運氣request.set(「範圍」,「https://www.googleapis.com/auth/calendar」)。還嘗試設置response_type,grant_type,任何幫助將不勝感激。下面是代碼(附件以及Maven項目):

Test.java

import com.google.api.client.auth.oauth2.draft10.AccessTokenErrorResponse; 
import com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant; 
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; 
import com.google.api.client.http.HttpResponseException; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.jackson.JacksonFactory; 
public class Test { 
    public static void main(String[] args) throws Exception { 
    try { 
     ResourceOwnerPasswordCredentialsGrant request = 
      new ResourceOwnerPasswordCredentialsGrant(
       new NetHttpTransport(), 
       new JacksonFactory(), 
       "https://accounts.google.com/o/oauth2/auth", 
       "<client_id>", 
       "<client_secret>", 
       "<user_username>", 
       "<user_password>"); 
     AccessTokenResponse response = request.execute(); 
     System.out.println("Access token: " + response.accessToken); 
    } catch (HttpResponseException e) { 
     AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class); 
     System.out.println("Error: " + response.error); 
    } 
    } 
} 

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>com.acme</groupId> 
    <artifactId>google-oauth</artifactId> 
    <version>1</version> 
    <name>Google OAuth</name> 
    <dependencies> 
     <dependency> 
      <groupId>com.google.api.client</groupId> 
      <artifactId>google-api-client</artifactId> 
      <version>1.4.1-beta</version> 
     </dependency> 
    </dependencies> 
    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 
</project> 

回答

1

的谷歌的OAuth2.0授權服務器不支持資源所有者密碼憑據流。如果您提供了避免基於Web的用戶界面的原因,可能有一些解決方法可用 - 例如,企業設置中的service accounts,您的應用程序可以代表用戶執行操作。

+0

如果Google不支持資源所有者密碼憑據,那麼爲什麼要包含com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant類? – SergeyB

+0

@ike_love基於我的閱讀,Google將包含一個包含「資源所有者密碼憑證」的類,其中有兩個可能的原因:他們使圖書館標準兼容,以便人們可以將其與其他OAuth2服務器一起使用,和/或他們正在吃自己的狗糧,並在自己的Google Sign-In網絡應用程序中使用此庫。 –

相關問題