我正在尝试创建桌面应用程序,该应用程序允许列出Google云端硬盘帐户中的文件和文件夹。在这个问题上,我能够做到,但有一个问题。每次我想从我的应用程序打开谷歌驱动器帐户时,我必须重新登录。是否可以使用存储的本地AccessToken / Refresh令牌以避免每次重新授权?
此处用于获取授权的方法。
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);
}
解决:
要首先从Google云端硬盘sdk调用方法,您需要服务实例:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, GoogleDriveHelper.CLIENT_ID, GoogleDriveHelper.CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
Service = new DriveService(auth);
您在Google API控制台中注册申请后将拥有的CLIENT_ID和CLIENT_SECRET。
然后,您需要定义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;
}
如果您已经拥有刷新和访问令牌(至少刷新),它将起作用。因此,您需要先为某些用户帐户进行授权。
然后您可以使用该Service实例来调用sdk方法。 希望它会帮助别人。