2012-11-06 2 views
5

데이터베이스에 저장된 '새로 고침 토큰'을 기반으로 새로운 '액세스 토큰'을 가져오고 싶습니다.(JAVA) Google API 분석 - '토큰 새로 고침'을 사용하여 새 '액세스 토큰'을 가져올 수 없음

com.google.api.client.auth.oauth2.TokenResponseException : 400 잘못된

요청

GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder() 
     .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) 
     .setClientSecrets(CLIENT_ID, CLIENT_SECRET); 
credentialBuilder.addRefreshListener(new MyCredentialRefreshListener()); 

credential = credentialBuilder.build(); 
credential.setRefreshToken("saved_refresh_token_from_database"); 

try { 
    credential.refreshToken(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 


class MyCredentialRefreshListener implements CredentialRefreshListener { 
    public void onTokenResponse(Credential cr, TokenResponse tr) { 
     System.out.println("Credential was refreshed successfully."); 
    } 

    public void onTokenErrorResponse(Credential cr, TokenErrorResponse tr) { 
     System.out.println(tr); 
    } 
} 

나는이 메시지가 : 여기

내가 쓴 코드 { "error": "invalid_grant"}

동일한 CLIENT_ID, CLIE NT_SECRET 및 "새로 고침 토큰"PHP 스크립트에서 거기에 "액세스 토큰"만료되면 "새로 고침 토큰"을 사용하여 새 "액세스 토큰"얻을 관리.

나는 javadoc.google-oauth-java-client을 기반으로 코드를 작성했습니다.

여기에있는 사람이 누구나 새로운 액세스 토큰을 얻기 위해 코드를 수정하는 방법을 알고 있습니까?

미리 감사드립니다.

업데이트 : 문제는 데이터베이스에 json_decode를 수행하지 않고 refresh_token을 저장하고 JSON에서 이스케이프 된 문자로 간주되는 "\"가 포함되어 있다는 것이 었습니다.

+0

나는 당신의 코드를 시험해 보았고, 저에게 도움이되었습니다. 제 생각 엔 당신의 새로 고침 토큰과 관련된 데이터/형식 문제였습니다. – user1697575

답변

2

일부 오래된 문서를 찾은 것 같습니다. 링크 된 JavaDoc은 클라이언트 라이브러리 버전 1.8에 대한 것입니다. 현재 버전은 1.12입니다.

클라이언트 라이브러리 작성자는 GoogleAuthorizationCodeFlow을 사용하여 OAuth 자격증 명을 관리 할 것을 권장합니다. 자동으로 새로 고침을 처리합니다. 이 경로를 따르면 코드는 http 상태 400이 표시되고 메시지가 "invalid_grant"인 경우

// Create the flow 
AuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
    new UrlFetchTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, 
    Collections.singleton(OAUTH_SCOPES)) 
    .setAccessType("offline") 
    .setCredentialStore(new AppEngineCredentialStore()) 
    .build(); 

// User Id: e.g. from session 
Credential credential = authorizationCodeFlow.loadCredential(USER_ID);  

// Make your API call. This example uses the Google+ API 
// If the access token has expired, it will automatically refresh 
Plus plus = new Plus(new UrlFetchTransport(), new JacksonFactory(), credential) 
    .activities().list("me", "public").execute(); 
1

과 같이 표시됩니다. HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET의 인스턴스를 확인해야한다고 생각합니다.

관련 문제