com.google.gdata.util.AuthenticationException: ошибка аутентификации (проверьте имя службы)
Я пытаюсь использовать API аудита электронной почты для моей G Suite. Я соединяюсь с администратором моего домена. Это мой код:
package com.archivage.gmail;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.appsforyourdomain.audit.AuditService;
import com.google.gdata.client.appsforyourdomain.audit.MailBoxDumpRequest;
import com.google.gdata.client.appsforyourdomain.audit.MailMonitor;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
// HTTP GET request
// HTTP POST request
public static void sendPost(String domain, String userId) throws Exception {
String url = "https://apps-apis.google.com/a/feeds/compliance/audit/mail/monitor/" + domain + "/" + userId;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
System.out.println("testing url");
con.setRequestProperty("Content-Type","application/atom+xml");
// con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("destUserName","user");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// wr.writeBytes(urlParameters);
// System.out.println(response.toString());
File p12 = new File("/path/key.p12");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String[] SCOPESArray = {"https://apps-apis.google.com/a/feeds/compliance/audit", "https://www.googleapis.com/auth/userinfo.email"};
final List SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("8888990087766.apps.googleusercontent.com")
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(p12)
.build();
MailBoxDumpRequest mailboxDumpRequest = new MailBoxDumpRequest();
mailboxDumpRequest.setBeginDate(new Date());
mailboxDumpRequest.setEndDate(new Date());
mailboxDumpRequest.setIncludeDeleted(true);
mailboxDumpRequest.setSearchQuery("in:chat");
mailboxDumpRequest.setPackageContent("FULL_MESSAGE");
MailMonitor monitor = new MailMonitor();
Calendar endDate = Calendar.getInstance();
endDate.set(2017, Calendar.AUGUST, 30, 23, 20);
monitor.setEndDate(endDate.getTime());
monitor.setChatMonitorLevel("HEADER_ONLY");
monitor.setDestUserName("user@domain.pro");
AuditService service = new AuditService("admin@domain.pro", "password", "domain.pro", "project-id");
// GenericEntry entry = service.createMailMonitor("user@domain.pro", monitor);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
//System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Calendar fromDate = Calendar.getInstance();
// GenericEntry mailboxDumpEntry2 = service.retrieveMailboxDumpRequest("user@domain.pro", "10");
// String status = mailboxDumpEntry2.getProperty("status");
fromDate.set(2017, Calendar.AUGUST, 30, 21, 0);
List<GenericEntry> mailboxDumpRequestEntries = service.retrieveAllMailboxDumpRequests(fromDate.getTime());
for (GenericEntry entry : mailboxDumpRequestEntries) {
MailBoxDumpRequest request = new MailBoxDumpRequest(entry);
String status = request.getStatus();
service.setOAuth2Credentials(credential);
GenericEntry dumpRequest = service.createMailboxDumpRequest(mailboxDumpRequest);
System.out.println(dumpRequest.toString());
}
}
}
package com.archivage.gmail;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.HttpResponse;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
@SpringBootApplication
public class GmailApplication {
public static void main(String[] args) {
SpringApplication.run(GmailApplication.class, args);
try {
HttpURLConnectionExample.sendPost("doamin.pro","user@domain.pro");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Я получил эту ошибку в консоли:
com.google.gdata.util.AuthenticationException: ошибка аутентификации (проверьте имя службы) на com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:688) на com.google.gdata.client.GoogleAuthTokenFactory.enAuthTuthTuthTuthTuthTuth.java:560) на com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397) на com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364) на com.google.google.client.GoogleService.setUserCredentials(GoogleService.java:319) на com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303) на com.google.gdata.client.appsforyourdomain.audit.AuditService (AuditService).:77) в com.archivage.gmail.HttpURLConnectionExample.sendPost(HttpURLConnectionExample.java:91) в com.archivage.gmail.GmailApplication.main(GmailApplication.java:28) в sun.reflect.NativeMethodAccessorImpl.invoke (Native) (0) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke(Method.java:498) в org.stome.run(RestartLauncher.java:49)