问题描述
我有一个像这样的OAuth2令牌...
I have an OAuth2 token like this...
{{
"access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"expires_in": "3600",
"refresh_token": "xxxxxxxxxxxxxxxxxx",
"token_type": "Bearer",
}}
并且我正在尝试创建一个DriveService对象...
and I'm trying to create a DriveService object...
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "foo",
});
(像这样吗?)
但是我显然不能正确执行此操作,并且在查找文档时遇到了麻烦.
but I'm clearly not doing this properly and I'm having trouble finding documentation.
当我尝试创建GoogleCredential
传递给DriveService
GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);
我收到以下异常:
{System.InvalidOperationException:从JSON创建凭据时出错.无法识别的凭证类型.
我会完全以错误的方式解决这个问题吗?
Am I going about this the wrong way entirely?
(这是示例代码上下文 )
推荐答案
我设法弄清楚了这一点.
I have managed to figure this out.
解决方案是使用我的ClientID和ClientSecret创建Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow
...
The solution was to create a Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow
with my ClientID and ClientSecret...
Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow googleAuthFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
ClientSecrets = new ClientSecrets()
{
ClientId = ClientID,
ClientSecret = ClientSecret,
}
});
以及Google.Apis.Auth.OAuth2.Responses.TokenResponse
:
Google.Apis.Auth.OAuth2.Responses.TokenResponse responseToken = new TokenResponse()
{
AccessToken = SavedAccount.Properties["access_token"],
ExpiresInSeconds = Convert.ToInt64(SavedAccount.Properties["expires_in"]),
RefreshToken = SavedAccount.Properties["refresh_token"],
Scope = GoogleDriveScope,
TokenType = SavedAccount.Properties["token_type"],
};
并使用每个参数创建一个UserCredential
,该UserCredential
依次用于初始化DriveService ...
and use each to create a UserCredential
that is, in turn, used to initialize the DriveService...
var credential = new UserCredential(googleAuthFlow, "", responseToken);
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "com.companyname.testxamauthgoogledrive",
});
我将 TestXamAuthGoogleDrive测试工具项目更新为反映这些变化.
I updated the TestXamAuthGoogleDrive test harness project to reflect these changes.
这篇关于如何通过授权的access_token创建GoogleCredential?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!