如何在 OAUTH 中使用 google 电子邮件审核 API(特别是 createMailMonitor)

how to use google email audit API (particularly createMailMonitor) with OAUTH

总结:我需要帮助获取服务(开发人员控制台中的服务帐户)进行身份验证,以便能够创建邮件监视器(电子邮件审核 API)

我读过最多的 relevant/official 页是:

developers.google.com/admin-sdk/email-audit/auth

developers.google.com/identity/protocols/OAuth2 developers.google.com/identity/protocols/OAuth2服务帐号

我读过几个例子,但它们要么是旧的(在 oauth 成为强制性之前),要么是用于客户端应用程序(在用户同意的情况下)。

下面的代码收到错误 401(需要授权),因为它缺少在这种情况下进行身份验证的代码。

HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
  .setTransport(httpTransport)
  .setJsonFactory(jsonFactory)
  .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
  .setServiceAccountScopes(Arrays.asList("https://apps-apis.google.com/a/feeds/compliance/audit/ https://www.googleapis.com/auth/userinfo.email"))
  .setServiceAccountUser(<account user>)
  .setServiceAccountPrivateKeyFromP12File(new java.io.File(<PKCS12_FILE_PATH>))
  .build();

MailMonitor monitor = new MailMonitor();

Calendar beginDate = Calendar.getInstance();
beginDate.set(2009, Calendar.JUNE, 15, 0, 0);
monitor.setBeginDate(beginDate.getTime());
Calendar endDate = Calendar.getInstance();
endDate.set(2009, Calendar.JUNE, 30, 23, 20);
monitor.setEndDate(endDate.getTime());
monitor.setIncomingEmailMonitorLevel("FULL_MESSAGE");
monitor.setOutgoingEmailMonitorLevel("HEADER_ONLY");
monitor.setDraftMonitorLevel("FULL_MESSAGE");
monitor.setChatMonitorLevel("FULL_MESSAGE");
monitor.setDestUserName(<user name>);

AuditService service_audit = new AuditService(<domain>, <app id>);

//WHAT CODE DO I INSERT HERE TO AUTHORIZE THIS SERVICE?
//I've tried : 
//service_audit.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
//but it requires Consumer Secret, etc which are only relevant for web applications where there is no user consent

GenericEntry entry = service_audit.createMailMonitor(<user id to monitor>, monitor);

我看过其他 APIs 使用 method Builder 的示例,例如:

Reports service = new Reports.Builder(httpTransport, jsonFactory, null)
  .setHttpRequestInitializer(credential).build();

所以我也尝试了下面的方法,但是我得到了一个找不到的符号:

AuditService service = new AuditService.Builder(httpTransport, jsonFactory, null)
  .setHttpRequestInitializer(credential).build();

我错过了什么?我可以得到一些关于如何从这里移动的指示吗?

非常感谢!

找到答案...也许其他人可以从中受益。

缺少的代码是

credential.refreshToken();
service.setOAuth2Credentials(credential);