我一直在使用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
,它们将被覆盖吗?还是我必须先删除旧的? (如何?)我一直在使用Google OAuth来允许用户授权访问我的Web应用程序的日历服务。经过成功的三足身份验证流程后,我将所有用户的凭据存储在一个公共文件中...
您可以使用端点https://www.googleapis.com/oauth2/v1/tokeninfo确定OAuth2令牌是否仍然有效。 OAuth2 guide中提供了更多信息。
您可以为此使用refreshToken()方法。参见示例:
回答第一个问题:
您可以使用tokeninfo来检查令牌,如果令牌无效:-从数据存储中删除凭据-调用新的身份验证