Java OAuth-无效令牌:不允许时使用请求令牌

Java OAuth-无效令牌:不允许时使用请求令牌,java,oauth,google-docs-api,Java,Oauth,Google Docs Api,我正试图用OAuth2.0访问Google的文档列表API 3.0,但我遇到了401错误 用户接受后,我的代码如下: GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); oauthParameters.setOAuthConsumerKey(CLIENT_ID); oauthParameters.setOAuthConsumerSecret(CLIENT_SECRET); oauthParameters.set

我正试图用OAuth2.0访问Google的文档列表API 3.0,但我遇到了401错误

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

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>

您使用的不是OAuth 2.0,而是OAuth 1.0和HMAC-SHA1作为签名方法。要使用OAuth2.0,您至少需要1.47.0版本的库和1.8.0-beta版本的库

使用该库提供帮助类来处理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());
  }

  // …
}
import com.google.api.client.auth.oauth2.Credential;
导入com.google.api.client.GoogleAppis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
导入com.google.api.client.GoogleAppis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
导入com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
导入com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.http.javanet.NetHttpTransport;
导入com.google.api.client.json.jackson.JacksonFactory;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.array;
导入java.util.List;
公共类MyClass{
//从API控制台项目检索客户端ID和客户端机密:
//     https://code.google.com/apis/console
静态字符串CLIENT_ID=“”;
静态字符串CLIENT_SECRET=“”;
//将REDIRECT_URI值更改为已注册的web重定向URI
//应用程序。
静态字符串重定向_URI=“urn:ietf:wg:oauth:2.0:oob”;
//添加其他请求的作用域。
静态列表范围=数组。asList(“https://docs.google.com/feeds");
/**
*检索OAuth 2.0凭据。
* 
*@return OAuth 2.0凭据实例。
*/
静态凭据getCredentials()引发IOException{
HttpTransport传输=新的NetHttpTransport();
JacksonFactory jsonFactory=新JacksonFactory();
//步骤1:授权-->
字符串授权URL=
新的GoogleAuthorizationCodeRequestUrl(客户端ID、重定向URI、作用域);
//将用户指向或重定向到authorizationUrl。
System.out.println(“转到浏览器中的以下链接:”);
System.out.println(授权URL);
//从标准输入流中读取授权代码。
BufferedReader in=新的BufferedReader(新的InputStreamReader(System.in));
System.out.println(“授权码是什么?”);
字符串代码=in.readLine();
//第1步结束
GoogleTokenResponse=
新的GoogleAuthorizationCodeTokenRequest(传输、jsonFactory、客户端ID、客户端机密、,
代码,重定向_URI).execute();

//步骤2的末尾以下是如何将OAuth2.0令牌添加到GData服务:

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

service.setOAuth2Credentials(new Credential(BearerToken
    .authorizationHeaderAccessMethod())
    .setFromTokenResponse(new TokenResponse().setAccessToken(mToken)));
确保导入所有必要的库(这是非常多的)

应使用Google Play Services OAuth机制获取Android上的令牌:

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

您能将您的解决方案放入答案中并接受该答案吗?这样,问题将标记为已解决,如果任何人(出于任何原因)登上此帖子,答案将很容易找到。谢谢。您是对的。已修复了使用OAuth2运行的问题。但您的代码有一个错误,这句话是向后的:。setRefreshToken(response.getAccessToken()).setAccessToken(response.getRefreshToken());谢谢,我修复了示例:-)你能为这个jar google api java客户端提供maven依赖的链接吗?你去吧!这个答案完美地补充了投票最多的答案…@zavidovych你考虑过编辑另一个答案来丰富它吗?
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");

service.setOAuth2Credentials(new Credential(BearerToken
    .authorizationHeaderAccessMethod())
    .setFromTokenResponse(new TokenResponse().setAccessToken(mToken)));
String token = GoogleAuthUtil.getToken(String email, String scopes);