2012-04-20 17 views
5

Próbuję uzyskać dostęp do Google Documents List API 3.0 za pomocą OAuth 2.0, ale mam pewne problemy z błędem 401.OAuth - Nieprawidłowy token: Żeton żądania używany, gdy jest niedozwolony

Po użytkownik zaakceptował mój kod jest następujący:

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); 

Następnie, w ostatnim wierszu -getFeed() - rzuca wyjątek:

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> 

Co się dzieje? Na statycznej głównej klasie testowej działa jak czar, ale kiedy uruchomię go na serwerze, ta linia już nie działa. Dowolny pomysł?


SOLVED

Token dostęp musi być pobrana w ten sposób, ze GoogleOAuthHelper, nie z GoogleOAuthParameters bezpośrednio:

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

można umieścić swoje rozwiązania w odpowiedzi i przyjąć, że odpowiedź na to pytanie? W ten sposób pytanie jest oznaczane jako rozwiązane i jeśli ktokolwiek znajdzie się w tym poście (z dowolnego powodu), odpowiedź będzie łatwa do znalezienia. –

+0

Co to jest oauthHelper? –

Odpowiedz

13

Nie używasz OAuth 2.0 ale OAuth 1.0 z HMAC-SHA1 jako metodą podpisu. Aby używać OAuth 2.0, potrzebujesz przynajmniej wersji 1.47.0 biblioteki gdata-java-client i wersji 1.8.0-beta biblioteki google-oauth-java-client.

Korzystanie z biblioteki google-api-java-client zapewnia klasy pomocnicze do obsługi implementacji Google OAuth 2.0.

Aby pobrać OAuth 2.0 poświadczeń, można użyć tego fragmentu kodu:

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()); 
    } 

    // … 
} 

Gdy masz poświadczeń OAuth 2.0, można zezwolić obiektu serwisowego następujące:

// ... 
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 , CLIENT_SECRET można pobrać z APIs Console, a REDIRECT_URI musi być zgodny z zarejestrowanym w twoim projekcie API.

+0

Dzięki. Miałeś rację. Naprawiono już uruchamiane z OAuth2. Ale twój kod zawiera błąd, to zdanie jest cofnięte: .setRefreshToken (response.getAccessToken()). SetAccessToken (response.getRefreshToken()); – xuso

+0

Dzięki, poprawiłem próbkę :-) – Alain

+0

czy możesz podać link do zależności dla maven dla tego słoika google-api-java-client? – Sanket

3

Oto jak dodać OAuth2.0 token GData Service:

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

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

Upewnij importować wszystkie potrzebne biblioteki (które jest dużo).

Na Android tokena należy uzyskać za pomocą usługi Google Play OAuth mechanizm:

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

Ta odpowiedź doskonale pasuje do najczęściej wybieranej ... @ zavidovych czy rozważałeś edytowanie innej odpowiedzi, aby ją wzbogacić? –

Powiązane problemy