com.google.api.client.auth.oauth2.TokenResponseException Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.TokenResponseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleCredentialFactory.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Refreshes and updates the given credential */
public Credential refreshCredential(Credential credential)
    throws IOException, InvalidTokenException {
  try {
    TokenResponse tokenResponse =
        new RefreshTokenRequest(
                httpTransport,
                jsonFactory,
                new GenericUrl(credential.getTokenServerEncodedUrl()),
                credential.getRefreshToken())
            .setClientAuthentication(credential.getClientAuthentication())
            .setRequestInitializer(credential.getRequestInitializer())
            .execute();

    return credential.setFromTokenResponse(tokenResponse);
  } catch (TokenResponseException e) {
    TokenErrorResponse details = e.getDetails();
    if (details != null && details.getError().equals("invalid_grant")) {
      throw new InvalidTokenException("Unable to refresh token.", e);
    } else {
      throw e;
    }
  }
}
 
Example #2
Source File: GitLabContext.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static GitLabToken obtainAccessToken(@NotNull String gitlabUrl, @NotNull String username, @NotNull String password, boolean sudoScope) throws IOException {
  try {
    final OAuthGetAccessToken tokenServerUrl = new OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + (sudoScope ? "%20sudo" : ""));
    final TokenResponse oauthResponse = new PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute();
    return new GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.getAccessToken());
  } catch (TokenResponseException e) {
    if (sudoScope && e.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
      // Fallback for pre-10.2 gitlab versions
      final GitlabSession session = GitlabAPI.connect(gitlabUrl, username, password);
      return new GitLabToken(TokenType.PRIVATE_TOKEN, session.getPrivateToken());
    } else {
      throw new GitlabAPIException(e.getMessage(), e.getStatusCode(), e);
    }
  }
}
 
Example #3
Source File: OAuthExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public BackgroundException map(final TokenResponseException failure) {
    final StringBuilder buffer = new StringBuilder();
    final TokenErrorResponse details = failure.getDetails();
    if(null != details) {
        this.append(buffer, details.getErrorDescription());
    }
    return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getStatusCode(), buffer.toString()));
}
 
Example #4
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Method exchanges the authorization code for an access token. 
 * If successful the Tokens and Expiration Date will be stored.
 * 
 * @param code The authorization code from the user interface response has to be passed
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public void requestAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   TokenResponse response =
       new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
           .setRedirectUri("https://localhost")
           .setGrantType("authorization_code")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")).execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
 }
}
 
Example #5
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Methods uses the refresh Token to retrieve a renewed access token
 * 
 * @param code Refresh Token
 * @return This returns if the request was successful.
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public boolean requestRefreshAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   RefreshTokenRequest request =
       new RefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
       	  .setRefreshToken(code)
       	  .set("redirect_uri", "https://localhost")
           .setGrantType("refresh_token")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7"));
   
   TokenResponse response = request.execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
   
   return true;
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
   return false;
 }
}
 
Example #6
Source File: GcpCredentialConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudCredentialStatus verify(@Nonnull AuthenticatedContext authenticatedContext) {
    LOGGER.debug("Verify credential: {}", authenticatedContext.getCloudCredential());
    GcpStackUtil.prepareCredential(authenticatedContext.getCloudCredential());
    GcpContext gcpContext = gcpContextBuilder.contextInit(authenticatedContext.getCloudContext(), authenticatedContext, null, null, false);
    try {
        gcpCredentialVerifier.checkGcpContextValidity(gcpContext);
        gcpCredentialVerifier.preCheckOfGooglePermission(gcpContext);
    } catch (TokenResponseException te) {
        return createFailedCloudCredentialStatusWithExc(te, authenticatedContext, getErrDescriptionFromTokenResponse(te));
    } catch (Exception e) {
        return createFailedCloudCredentialStatusWithExc(e, authenticatedContext, Optional.empty());
    }
    return new CloudCredentialStatus(authenticatedContext.getCloudCredential(), CredentialStatus.VERIFIED);
}
 
Example #7
Source File: GcpCredentialConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to get the "error_description" parameter's value from the given
 * TokenResponseException's content. If there is no "error_description"
 * parameter, or it has no value or something occurs during the process, an
 * empty Optional would return.
 *
 * @param e The TokenResponseException which content should have a
 *          "error_description" parameter with a string value.
 * @return A String Optional with the content of the "error_description"
 * from the exception, or an empty one.
 */
private Optional<String> getErrDescriptionFromTokenResponse(TokenResponseException e) {
    try {
        ObjectNode objectNode = new ObjectMapper().readValue(e.getContent(), ObjectNode.class);
        if (objectNode.has("error_description")) {
            return Optional.of(objectNode.get("error_description").asText());
        } else {
            return Optional.empty();
        }
    } catch (IOException ioe) {
        LOGGER.debug("Could not parse TokenResponseException", ioe);
        return Optional.empty();
    }
}
 
Example #8
Source File: OAuthManager.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the Android application to access user's protected data using
 * the Implicit Authorization flow in OAuth 2.0.
 * 
 * @param userId user ID or {@code null} if not using a persisted credential
 *            store
 * @param callback Callback to invoke when the request completes,
 *            {@code null} for no callback
 * @param handler {@link Handler} identifying the callback thread,
 *            {@code null} for the main thread
 * @return An {@link OAuthFuture} which resolves to a {@link Credential}
 */
public OAuthFuture<Credential> authorizeImplicitly(final String userId,
        final OAuthCallback<Credential> callback, Handler handler) {
    Preconditions.checkNotNull(userId);

    final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {

        @Override
        public void doWork() throws TokenResponseException, Exception {
            try {
                LOGGER.info("authorizeImplicitly");
                Credential credential = mFlow.loadCredential(userId);
                if (credential != null && credential.getAccessToken() != null
                        && (credential.getRefreshToken() != null ||
                                credential.getExpiresInSeconds() == null ||
                        credential.getExpiresInSeconds() > 60)) {
                    set(credential);
                    return;
                }

                String redirectUri = mUIController.getRedirectUri();

                BrowserClientRequestUrl authorizationUrl = mFlow.newImplicitAuthorizationUrl()
                        .setRedirectUri(redirectUri);
                mUIController.requestAuthorization(authorizationUrl);

                ImplicitResponseUrl implicitResponse = mUIController
                        .waitForImplicitResponseUrl();
                credential = mFlow.createAndStoreCredential(implicitResponse, userId);
                set(credential);
            } finally {
                mUIController.stop();
            }
        }

    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}