我有一个像这样的 OAuth2 token ......
{{
"access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"expires_in": "3600",
"refresh_token": "xxxxxxxxxxxxxxxxxx",
"token_type": "Bearer",
}}
我正在尝试创建一个 DriveService 对象...
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "foo",
});
(像这样?)
但我显然没有正确执行此操作,并且在查找文档时遇到了麻烦。
当我尝试创建
GoogleCredential
时传递给 DriveService
GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);
我收到以下异常:
{System.InvalidOperationException:从 JSON 创建凭据时出错。无法识别的凭据类型。
我是否完全以错误的方式解决这个问题?
(这是 the sample code context )
最佳答案
我设法弄明白了这一点。
解决方案是创建一个 Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow
使用我的 ClientID 和 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...var credential = new UserCredential(googleAuthFlow, "", responseToken);
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "com.companyname.testxamauthgoogledrive",
});
我更新了 TestXamAuthGoogleDrive test harness project来反射(reflect)这些变化。
关于oauth-2.0 - 如何从授权的 access_token 创建 GoogleCredential?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337136/