use of com.google.api.services.oauth2.model.Tokeninfo in project dockstore by dockstore.
the class GoogleHelper method tokenInfoFromToken.
private static Optional<Tokeninfo> tokenInfoFromToken(String googleToken) {
GoogleCredential cred = new GoogleCredential().setAccessToken(googleToken);
try {
Oauth2 oauth2 = new Oauth2.Builder(TokenResource.HTTP_TRANSPORT, TokenResource.JSON_FACTORY, cred).setApplicationName("").build();
Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(googleToken).execute();
return Optional.ofNullable(tokenInfo);
} catch (RuntimeException | IOException e) {
// If token is invalid, Google client throws exception. See https://github.com/google/google-api-java-client/issues/970
LOG.info(MessageFormat.format("Error getting token info: {0}", e.getMessage()));
LOG.debug("Error getting token info", e);
return Optional.empty();
}
}
use of com.google.api.services.oauth2.model.Tokeninfo in project dockstore by dockstore.
the class GoogleHelper method getValidAccessToken.
/**
* Gets a non-expired access token.
*
* Google access tokens expire. This method returns
* an active access token, either returning the one
* that is in <code>token</code>, or generating a new
* one with the refresh token, if necessary.
*
* This method does NOT update the <code>token</code> with the new token,
* if there is one. It is the responsibility of the caller to update
* the token if they want the new token to be persisted.
*
* @param token
* @return
*/
public static Optional<String> getValidAccessToken(Token token) {
final String googleToken = token.getToken();
return tokenInfoFromToken(googleToken).map(tokenInfo -> {
// The user has a non-expired Google token -- also make sure that the audience is valid.
return isValidAudience(tokenInfo) ? Optional.of(googleToken) : Optional.<String>empty();
}).orElseGet(() -> {
// The token expired; try to refresh it
if (token.getRefreshToken() != null) {
TokenResponse tokenResponse = new TokenResponse();
try {
tokenResponse.setRefreshToken(token.getRefreshToken());
GoogleCredential credential = new GoogleCredential.Builder().setTransport(TokenResource.HTTP_TRANSPORT).setJsonFactory(TokenResource.JSON_FACTORY).setClientSecrets(config.getGoogleClientID(), config.getGoogleClientSecret()).build().setFromTokenResponse(tokenResponse);
credential.refreshToken();
return Optional.ofNullable(credential.getAccessToken());
} catch (IOException e) {
LOG.error("Error refreshing token", e);
}
}
return Optional.empty();
});
}
Aggregations