2017-06-02 29 views
0

我有一個的OAuth2令牌是這樣的...如何從授權的access_token創建GoogleCredential?

{{ 
    "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

+0

我對C#並不熟悉,但我認爲有一本關於[C#中的OAuth 2.0]的指南(https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web- applications-aspnet-mvc)將幫助您使用授權的access_token創建driveService。這也將提供區分用戶憑證和ServiceAccountCredential的指南。希望這可以幫助。 –

回答

1

我設法想出解決辦法。

的解決方案是創建一個客戶端ID我和ClientSecret一個Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow ...

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以反映這些更改。

相關問題