【发布时间】:2021-12-29 01:35:14
【问题描述】:
在现有的基于 Java 的 Spring Boot 应用程序中,我集成了 Google 日历 API。在我当地,它有效。在开发服务器上,我看到要在浏览器中打开的 URL 是:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=xxx.apps.googleusercontent.com&redirect_uri=http://localhost:8080/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.events
重定向 uri 是 http://localhost:8080/Callback 而不是 https://dev.myserver.in/Callback,这会导致无效请求
即使我手动更正 URI 并在浏览器中过去,它也会显示 404。
我已经创建了服务帐户并为 localhost 和我的开发服务器提供了重定向 uri,并且我在我的代码中使用了与 credential.json 文件相同的文件。
以下是代码sn-ps
private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = GoogleCalendarServiceImpl.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + 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 java.io.File(tokensDirectoryPath)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); //.Builder().setPort(localServerReceiverPort).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
在这里使用它:
public void createEvent(CreateEventRequest request) throws GeneralSecurityException, IOException {
// 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 = createEvent(request);
String calendarId = "primary";
Event createdEvent = service.events().insert(calendarId, event).execute();
log.info("Event successfully created! : {} ", createdEvent.getHtmlLink());
}
这里是配置:
private static final String APPLICATION_NAME = "Calendar";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String CREDENTIALS_FILE_PATH = "/credential.json";
@Value("${google.calendar.tokens.directory.path}")
private String tokensDirectoryPath
/**
* Global instance of the scopes required by this quickstart. If modifying these
* scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_EVENTS);
【问题讨论】:
标签: java spring-boot google-oauth google-calendar-api google-api-java-client