.NET Google api 1.7 beta使用刷新令牌进行身份validation

我一直在关注Oauth .Net Google Apis,以便通过OAuth进行身份validation并使用Google驱动Apis。

具体来说,我想使用我已经存储的刷新令牌,以便使用它来实例化GoogleDrive服务。

我找到了像https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples这样的示例

这似乎使用“GoogleWebAuthorizationBroker.AuthorizeAsync”,但我不确定如何使用该方法使用刷新令牌而不是您在此示例中似乎提供的客户机密码。

如果我理解正确,您就会问如何基于现有的刷新令牌创建新的Google服务。

所以,你可以做到以下几点:

var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" }; var credentials = new UserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = [your_client_secrets_here] }), "user", token); 

然后,您可以将凭据传递给服务的初始化程序。

通过执行上述操作, GoogleAuthorizationCodeFlow将根据您刷新令牌和客户端机密获取新的访问令牌。

请注意,您必须在此处拥有客户机密码,否则您将无法获得访问令牌。

client_secrets.json包含客户端ID和客户端密钥(其中包含您的应用程序的OAuth 2.0信息)。

我认为本文将更好地解释OAuth 2.0如何访问Google Apps API,尤其是在构建Web应用程序时。

https://developers.google.com/accounts/docs/OAuth2WebServer

如果您对编码示例感兴趣,则stackoverflow中有一个: Google+ API:如何在每次启动应用时使用RefreshTokens来避免请求访问权限?

GoogleWebAuthorizationBroker要求您在发送FileDatastore的情况下发送iDataStore的信息。 FileDataStore将数据存储在%appData%中。 如果你想使用一个refreshtoken你保存在其他地方你需要创建自己的iDataStore限制。

实际数据存储区的代码在这里发布的时间不长。 http://daimto.com/google-oauth2-csharp/

然后就像使用FileDataStore一样使用它

 //Now we load our saved refreshToken. StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text); // Now we pass a SavedDatastore with our StoredResponse. using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store"; StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile }, "user", CancellationToken.None, new SavedDataStore(myStoredResponse)).Result; } 

该教程附有一个示例项目。