致力于从后端在特定日历上创建Google日历活动。就像有人在Web应用程序中生成会议一样,它应该从后端添加到共享的Google日历中(使用JAVA运行 - Spring启动)。
生成事件的用户必须是授权用户才能执行此操作。
我已经按照这个文档在java中进行初始设置。
我使用过的依赖关系,
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-calendar:v3-rev305-1.23.0'
然后创建一个我试过这个的事件,
public String createCalendarEvent() throws GeneralSecurityException, IOException {
String calendarId = "primary";
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
Event event = new Event()
.setSummary("Testing Event Creation 1")
.setLocation("India")
.setDescription("Testing Event Creation");
EventDateTime start = new EventDateTime()
.setDate(new DateTime("2019-02-26"));
event.setStart(start);
EventDateTime end = new EventDateTime()
.setDate(new DateTime("2019-02-28"));
event.setEnd(end);
event = service.events().insert(calendarId, event).execute();
log.debug("Event is created and HTML link is: " + event.getHtmlLink());
return event.getHtmlLink();
}
getCredential()
方法正在处理授权如下:
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = CalendarEventService.class.getClassLoader().getResourceAsStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
return credential;
}
所需的OAuth ClientID和ClientSecret位于CREDENTIALS_FILE_PATH
。运行它时会在TOKENS_DIRECTORY_PATH
中生成AUTH_TOKEN并在Calendar中创建一个事件。
现在后续执行执行没有任何问题如果用户更改。
我需要由当前登录的用户(应检查OAuth)和后端as this one在日历中创建事件。
服务器到服务器通信未经同意
您需要了解私有用户数据始终要求您具有访问权限。在没有该用户权限的情况下,您无法访问用户帐户。 Oauth2为开发人员提供了一种请求用户同意访问其数据的方法。您无需经常获得用户访问其数据的权限。
现在,如果您有一个gsuite帐户,您可以使用服务帐户并设置域范围委派以允许服务帐户访问域中的所有用户,然后它将能够代表用户执行操作而无需提示任何人。
如果您只访问个人可以控制的单个帐户,那么您还可以使用服务帐户并与服务帐户共享日历,然后服务帐户将可以访问该帐户并能够对其执行操作。
凭证存储
new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)
表示凭据存储的位置"user"
是一个字符串,表示您要为其存储凭据的用户。