【发布时间】:2019-12-03 20:36:16
【问题描述】:
我一直在使用 Google OAuth 让用户授权访问我的 Web 应用程序的日历服务。在成功3-legged auth flow 之后,我将所有用户的凭据存储在应用服务器上的一个公共文件中。下次应用需要使用该服务时,它会检查凭据是否存在,如果存在,它将假定它们是有效的
代码就是这样工作的
@Override
public void _authorize(String userId) throws IOException {
// Check if user has already authorised the service.
Credential credents = flow.loadCredential(userId);
// Checking if the given user is not authorized
if (credents == null) {
//Create credentials now. user will be redirected to authorise
try {
//Creating a LocalServer Receiver
// Getting the redirect URI
// Creating a new authorization URL
// Setting the redirect URI
// Building the authorization URL
// Receiving authorization code
// Exchanging it for an access token
// Storing the credentials for later access
credents = flow.createAndStoreCredential(response, id);
} finally {
// Releasing resources
}
} else {
// Assume the credentials are valid. so there's nothing left to do here, let's get that client
//Update: Nooooooot! the user might have revoked the authorization, so credents != null BUT they are invalid
//TODO: handle an Exception here, and manage the revoked credentials
}
// Setting up the calendar service client
client = new com.google.api.services.calendar.Calendar.Builder(httpTransport, jsonFactory, credents).setApplicationName(APPLICATION_NAME)
.build();
}
只要用户从不改变主意,它就可以正常工作。但如果用户决定使用 Google 帐户安全选项manually revoke授权,则 com.google.api.services.calendar.Calendar 检索将失败。
我的问题是:
- 有没有办法检查凭证是否仍然有效,在尝试使用它们之前? 否则,我只能猜测无法获取客户端对象,这是让我的门户网站意识到凭据不再有效的唯一方法吗?
- 我应该如何处理无效/撤销的凭据?我应该只打电话给
flow.createAndStoreCredential他们会被覆盖吗?还是我必须先删除旧的? (怎么做?)
【问题讨论】:
-
如果凭据删除访问权限,他们不会返回 null 吗?试图找到删除访问权限的页面需要对此进行测试:)
-
@DaImTo no,[flow.loadCredential(id)] 仍然返回一个不会通过 CalendarService 初始化的凭证对象。据我所知,这很正常,因为我的门户没有通过任何其他方式通知用户已撤销身份验证
-
@DaImTo 我添加了指向 Google 帐户安全选项的链接。选择“撤销访问”按钮。说实话,这是一个隐藏得很好的功能,我怀疑大多数谷歌用户都知道这个选项:)
-
@yannicuLar 你找到解决方案了吗?我也遇到了同样的问题。
-
@DanielMarín 对不起,不!我已经做了一个解决方法,如果我有一个失败的服务调用,我将删除存储的通行证,因此将启动一个新的身份验证流程
标签: java google-calendar-api google-oauth