Reputation: 2229
I am trying to fetch some data from GoogleAnalytics through a java application running inside a VM.
I have a refresh token ready with me available and I want to use this refresh token to generate an auth token and eventually get data from GA.
This is how my current code looks like.
private static String getAccessToken(String refreshToken) throws IOException {
TokenResponse tokenResponse = new GoogleRefreshTokenRequest(httpTransport, JSON_FACTORY, refreshToken, googleClientId, googleClientSecret)
.setScopes(AnalyticsScopes.all())
.setGrantType("refresh_token")
.execute();
return tokenResponse.getAccessToken();
}
public Credential getCredentials() throws GeneralSecurityException, IOException, FileNotFoundException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
// Load client secrets.
InputStream in = GoogleAnalyticsDataImportService.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CLIENT_SECRET_JSON_RESOURCE);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
String clientId = clientSecrets.getDetails().getClientId();
String clientSecret = clientSecrets.getDetails().getClientSecret();
Credential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(clientId, clientSecret)
.build();
String refreshToken = "<REFRESH-TOKEN>"; //Find a secure way to store and load refresh token
credential.setAccessToken(getAccessToken(refreshToken));
credential.setRefreshToken(refreshToken);
return credential;
}
The issue here is that GoogleCredentials
is deprecated and I can't find a way to create the Credentials class without it to use refreshToken.
I also tried another flow, but this opens up the browser to get the user authenticated, but I don't want that. The frontend will handle the user authentication and I plan to store the refresh token in a database securely for future API access.
How can I use the refresh token and create a credentials class so that I can access Google Analytics Data?
Upvotes: 0
Views: 561
Reputation: 11
Based on the GoogleCredential class Java Doc you could look
https://github.com/googleapis/google-auth-library-java
I quick looked it. should be ok to get token by GoogleCredentials instead of the deprecated GoogleCredential
GoogleCredentials credentials = GoogleCredentials.fromStream(new
FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();
Upvotes: 1