我正在使用Google API Java客户端来管理从Java中的Google App Engine对Google Drive API的访问。
我得到一个用户访问令牌和刷新令牌,并将它们保存在我们的数据库中。不过,我认为只有刷新令牌需要持久化。
如何管理访问令牌过期?你对这个策略有什么看法:
登录到web应用程序后,我将从刷新令牌中获取访问令牌,并将其存储在会话中。如何从存储在数据库中的刷新令牌创建Google凭据对象?
当我访问驱动器操作时,在到期的情况下,我捕获401异常以重新创建访问令牌
我读过关于
凭据和凭据存储
但它似乎已被弃用。现在必须使用以下命令:
StoredCredential
..。有没有人有使用这个新界面的示例?
谢谢。
发布于 2014-05-17 22:44:48
如果你使用的是Drive API库,它将为你处理401个异常,只要你给它一个带有访问和刷新令牌的凭据。
下面是如何构建
对象的
..。您可以使用不同于的实现
:
public class ApiCredentialManager {
private DataStore dataStore;
//Put your scopes here
public static String[] SCOPES_ARRAY = { "https://www.googleapis.com/auth/admin.directory.user" };
private ApiCredentialManager() {
try {
dataStore = MemoryDataStoreFactory.getDefaultInstance().getDataStore("credentialDatastore");
} catch (IOException e) {
throw new RuntimeException("Unable to create in memory credential datastore", e);
}
}
public static ApiCredentialManager getInstance() {
if (instance == null)
instance = new ApiCredentialManager();
return instance;
}
public Credential getCredential(String username) throws Exception {
try {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.addRefreshListener(
new DataStoreCredentialRefreshListener(
username, dataStore))
.build();
if(dataStore.containsKey(username)){
StoredCredential storedCredential = dataStore.get(username);
credential.setAccessToken(storedCredential.getAccessToken());
credential.setRefreshToken(storedCredential.getRefreshToken());
}else{
//Do something of your own here to obtain the access token.
//Most usually redirect the user to the OAuth page
}
return credential;
} catch (GeneralSecurityException e) {
throw new Exception("isuue while setting credentials", e);
} catch (IOException e) {
e.printStackTrace();
throw new Exception("isuue while setting credentials", e);
}
}
//Call this when you've obtained the access token and refresh token from Google
public void saveCredential(String username, Credential credential){
StoredCredential storedCredential = new StoredCredential();
storedCredential.setAccessToken(credential.getAccessToken());
storedCredential.setRefreshToken(credential.getRefreshToken());
dataStore.set(username, storedCredential);
}
}https://stackoverflow.com/questions/23083982
复制相似问题