[英]Managing Access Token with Google Drive Oauth 2.0
我正在使用 Google API Java 客戶端來管理從 Java 中的 Google App Engine 對 Google Drive API 的訪問。
我得到一個用戶訪問令牌和刷新令牌,並將它們保存在我們的數據庫中。 雖然,我認為只有刷新令牌需要持久化。
如何管理訪問令牌過期? 你怎么看這個策略:
一旦我登錄到我的 Web 應用程序,我就會從我的刷新令牌中獲取一個訪問令牌並將其存儲在會話中。 我必須如何從存儲在數據庫中的刷新令牌創建 Google 憑據對象?
當我訪問 Drive 操作時,如果過期,我會捕獲 401 異常以重新創建 Access Token
我已經閱讀了Credential 和 Credential Store,但它似乎已被棄用。 現在必須使用: StoredCredential 。 有人有使用這個新界面的示例嗎?
謝謝。
如果您使用 Drive API 庫,它會為您處理 401 異常,只要您為其提供帶有訪問和刷新令牌的憑據。
以下是如何使用StoredCredential
構建Credential
對象。 您可以使用不同於MemoryDataStoreFactory
的實現:
public class ApiCredentialManager {
private DataStore<StoredCredential> 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.