Currently, I am using the following implementation but the code says GoogleCredential is deprecated.
GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(clientId, clientSecret)
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.build();
credential.setRefreshToken(refreshToken);
I checked and GoogleCredentials or other google-auth-library classes are supposed to be used. However, all of them seem to require a service account. GoogleCredential is working for me without a service account. Just had to create oauth credentials. I have also generated the refresh tokens but not sure how to use them with the new library. What should I be using here? The goal is to just allow a single user(our backend code) to access google api.
I don't see any other questions for java where this was actually answered.
Edit - Posting my entire set up based on the comment updates-
public Credentials getCredentials() throws GeneralSecurityException, IOException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
try(InputStream in = getCredentialsAsInputStream()) {
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
String clientId = clientSecrets.getDetails().getClientId();
String clientSecret = clientSecrets.getDetails().getClientSecret();
Credentials credential = UserCredentials.newBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRefreshToken(refreshToken)
.build();
return credential;
And for setting up the drive
public Drive getDriveService() {
try {
Credentials credential = getCredentials();
HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(credential);
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, httpRequestInitializer)
.setApplicationName(DRIVE_API_APPLICATION_NAME)
.setHttpRequestInitializer(httpRequest -> {
httpRequestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(2 * 60000); // 2 minutes connect timeout
httpRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout
})
.build();
} catch (GeneralSecurityException | IOException e){
log.error("Error creating drive service class : {}", e);
}
return null;
}