我正在嘗試創建桌面應用程序,該應用程序允許在Google雲端硬盤帳戶中列出文件和文件夾。在這方面,我可以做到,但有一個問題。每次我想從我的應用程序中打開Google Drive帳戶時,我都必須重新登錄。是否可以使用存儲在本地的AccessToken/Refresh令牌來避免每次重新授權?使用存儲的憑證進行授權。 Google Drive API for .NET
這裏用來獲得授權的方法。
private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" });
// Get the auth URL:
state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob");
UriBuilder builder = new UriBuilder(arg.RequestUserAuthorization(state));
NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query);
queryParameters.Set("access_type", "offline");
queryParameters.Set("approval_prompt", "force");
queryParameters.Set("user_id", email);
builder.Query = queryParameters.ToString();
//Dialog window wich returns authcode
GoogleWebBrowserAuthenticator a = new GooogleWebBrowserAuthenticator(builder.Uri.ToString());
a.ShowDialog();
//Request authorization from the user (by opening a browser window):
string authCode = a.authCode;
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
解決:
爲了調用從谷歌硬碟SDK方法,首先你需要服務的一個實例:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, GoogleDriveHelper.CLIENT_ID, GoogleDriveHelper.CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
Service = new DriveService(auth);
那些CLIENT_ID和CLIENT_SECRET你註冊之後,你將有用於在Google API控制檯中應用。
然後,你需要定義GetAuthorization程序,該程序可能看起來如下:
private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" });
state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob");
state.RefreshToken = AccountInfo.RefreshToken;
state.AccessToken = AccountInfo.AccessToken;
arg.RefreshToken(state);
return state;
}
它將作品如果你已經有刷新和訪問令牌(至少刷新)。所以你需要先授權一些用戶帳戶。
然後,您可以使用該服務實例來調用sdk方法。 希望它能幫助別人。
好吧,我已經解決了它。 – Vlad
怎麼樣?你能分享一下嗎? – user990635
補充...讓我知道你是否會遇到問題 – Vlad