2012-04-20 242 views
5

我试图使用OAuth 2.0访问Google的文档列表API 3.0,但我遇到了401错误的一些麻烦。OAuth - 无效令牌:不允许使用请求令牌

用户后接受了,我的代码如下:

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
oauthParameters.setOAuthConsumerKey(CLIENT_ID); 
oauthParameters.setOAuthConsumerSecret(CLIENT_SECRET); 
oauthParameters.setOAuthToken(token); 
oauthParameters.setOAuthTokenSecret(tokenSecret); 
oauthParameters.setScope("https://docs.google.com/feeds/"); 

service = new DocsService("myapp"); 
service.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); 

DocumentListFeed feed = service.getFeed(new URL("https://docs.google.com/feeds/default/private/full/?v=3"), DocumentListFeed.class); 

然后,在最后一行-getFeed() - 抛出异常:

com.google.gdata.util.AuthenticationException: Token invalid - Invalid token: Request token used when not allowed. 
<HTML> 
<HEAD> 
<TITLE>Token invalid - Invalid token: Request token used when not allowed.</TITLE> 
</HEAD> 
<BODY BGCOLOR="#FFFFFF" TEXT="#000000"> 
<H1>Token invalid - Invalid token: Request token used when not allowed.</H1> 
<H2>Error 401</H2> 
</BODY> 
</HTML> 

这是怎么回事?在一个静态的主要测试类中就像一个魅力,但是当我在服务器上运行它时,这条线不再起作用。任何想法?


解决

访问令牌需要检索这种方式,具有GoogleOAuthHelper,不直接与GoogleOAuthParameters:

String accessToken = oauthHelper.getAccessToken(oauthParameters); 
+0

难道你把你的解决方案在回答中并接受的答案吗? 这种方式问题被标记为已解决,如果任何人在这篇文章(出于任何原因)获得答案将很容易找到。 – 2012-04-20 12:18:53

+0

这是什么oauthHelper? – 2012-08-14 09:12:17

回答

13

您没有使用OAuth 2.0但OAuth的1.0以HMAC-SHA1作为签名方法。要使用OAuth 2.0,至少需要gdata-java-client库的版本1.47.0和google-oauth-java-client库的1.8.0-beta版。

使用google-api-java-client库提供了helper类来处理Google的OAuth 2.0实现。

要检索OAuth 2.0凭证,您可以使用此代码片段:

import com.google.api.client.auth.oauth2.Credential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.jackson.JacksonFactory; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Arrays; 
import java.util.List; 

public class MyClass { 

    // Retrieve the CLIENT_ID and CLIENT_SECRET from an APIs Console project: 
    //  https://code.google.com/apis/console 
    static String CLIENT_ID = "<YOUR_CLIENT_ID>"; 
    static String CLIENT_SECRET = "<YOUR_CLIENT_SECRET>"; 
    // Change the REDIRECT_URI value to your registered redirect URI for web 
    // applications. 
    static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; 
    // Add other requested scopes. 
    static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds"); 

    /** 
    * Retrieve OAuth 2.0 credentials. 
    * 
    * @return OAuth 2.0 Credential instance. 
    */ 
    static Credential getCredentials() throws IOException { 
    HttpTransport transport = new NetHttpTransport(); 
    JacksonFactory jsonFactory = new JacksonFactory(); 

    // Step 1: Authorize --> 
    String authorizationUrl = 
     new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build(); 

    // Point or redirect your user to the authorizationUrl. 
    System.out.println("Go to the following link in your browser:"); 
    System.out.println(authorizationUrl); 

    // Read the authorization code from the standard input stream. 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("What is the authorization code?"); 
    String code = in.readLine(); 
    // End of Step 1 <-- 

    // Step 2: Exchange --> 
    GoogleTokenResponse response = 
     new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, 
      code, REDIRECT_URI).execute(); 
    // End of Step 2 <-- 

    // Build a new GoogleCredential instance and return it. 
    return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET) 
     .setJsonFactory(jsonFactory).setTransport(transport).build() 
     .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken()); 
    } 

    // … 
} 

一旦你熟悉OAuth 2.0认证,您可以授权服务对象为:

// ... 
import com.google.api.client.auth.oauth2.Credential; 
import com.google.gdata.client.docs.DocsService; 
import com.google.gdata.data.docs.DocumentListEntry; 
import com.google.gdata.data.docs.DocumentListFeed; 
import com.google.gdata.util.ServiceException; 
// ... 
import java.io.IOException; 
import java.net.URL; 
// ... 

public class MyClass { 
    // … 

    /** 
    * Print document entries using the provided authorized DocsService. 
    * 
    * @param credential OAuth 2.0 credential to use to authorize the requests. 
    * @throws IOException 
    * @throws ServiceException 
    */ 
    static void printDocuments(Credential credential) throws IOException, ServiceException { 
    // Instantiate and authorize a new DocsService object. 
    DocsService service = new DocsService("<YOUR_APPLICATION_NAME>"); 
    service.setOAuth2Credentials(credential); 

    // Send a request to the Documents List API to retrieve document entries. 
    URL feedUri = new URL("https://docs.google.com/feeds/default/private/full/"); 
    DocumentListFeed feed = service.getFeed(feedUri, DocumentListFeed.class); 

    for (DocumentListEntry entry : feed.getEntries()) { 
     System.out.println("Title: " + entry.getTitle().getPlainText()); 
    } 
    } 

    // ... 
} 

CLIENT_ID ,可以从APIs Console中检索CLIENT_SECRET,并且REDIRECT_URI必须与已在您的API项目中注册的相匹配。

+0

谢谢。你是对的。已修复已经可以使用OAuth2运行。但是你的代码有一个错误,这个句子是倒退:.setRefreshToken(response.getAccessToken())。setAccessToken(response.getRefreshToken()); – xuso 2012-04-23 14:30:39

+0

谢谢,我修复了这个示例:-) – Alain 2012-04-23 16:06:07

+0

你能为这个jar google-api-java-client提供maven dependency的链接吗? – Sanket 2013-01-29 13:26:30

3

这里是如何的OAuth2.0权杖加的GData服务:

SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1"); 

service.setOAuth2Credentials(new Credential(BearerToken 
    .authorizationHeaderAccessMethod()) 
    .setFromTokenResponse(new TokenResponse().setAccessToken(mToken))); 

确保导入所有必要的库(这是很多)。

在Android令牌应该使用谷歌播放服务的OAuth机制来获得:

String token = GoogleAuthUtil.getToken(String email, String scopes); 
+0

这个答案完美地补充了最多的一票...... @ zavidovych你有没有考虑编辑其他答案来丰富它? – 2015-10-12 01:42:08