我正在尝试通过在 VM 内运行的 Java 应用程序从 GoogleAnalytics 获取一些数据。
我有一个可用的刷新令牌,我想使用此刷新令牌生成一个身份验证令牌并最终从 GA 获取数据。
这是我当前代码的样子。
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;
}
这里的问题是 GoogleCredentials
已弃用,如果没有它使用 refreshToken,我找不到创建 Credentials 类的方法。
我还尝试了另一个流程,但这会打开浏览器以对用户进行身份验证,但我不想要那样。 前端将处理用户身份验证,我计划将刷新令牌安全地存储在数据库中以供将来 API 访问。
如何使用刷新令牌并创建凭据类以便我可以访问 Google Analytics 数据?