我正在尝试基于Spring Boot将Google Calendar API集成到我的一个Google App Engine项目中。使用基于JAVA的google-client-api库进行授权。我将在App Engine项目中创建的客户端ID和密码提供给GoogleAuthorizationCodeFlow
。第一次运行时,我得到一个用户同意屏幕,并在接受屏幕之后,在目标/令牌中创建了StoredCredential
文件。之后,我所有的Google Calendar API调用都可以正常工作。一段时间之后,我想这与访问令牌的过期有关,我再次获得了用户同意屏幕。根据文档,如果访问类型设置为offline
,则授权流程将负责管理刷新令牌。 StoredCredential
文件仍然在目标/令牌路径中,但是我仍然看到用户同意屏幕。授权代码的粘贴代码段。
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = EventController.class.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 java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static Calendar get() throws GeneralSecurityException, IOException {
// Build a new authorized API client com.huddle.processor.service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
}
更新: 在进行远程调试时,当google-oauth-client使用
从文件中获取存储的凭据时StoredCredential stored = credentialDataStore.get(userId);
刷新令牌为null。想知道这是否是原因,尽管不确定为什么没有设置。
如果有人能让我知道我在想什么,那将很棒。谢谢
答案 0 :(得分:1)
找到了解决方案。这与无法获取刷新令牌有关。需要传递的rovaling_prompt = force参数。因此更新的代码段为
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
对我有帮助的参考博客:https://googlecode.blogspot.com/2011/10/upcoming-changes-to-oauth-20-endpoint.html