如何从授权的 access_token 创建 GoogleCredential? [英] How do I create a GoogleCredential from an authorized access_token?
问题描述
我有一个像这样的 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
When I attempt to create a GoogleCredential
to pass to the 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
,依次用于初始化 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!