Search code examples
oauth-2.0google-drive-apidrive

How do I create a GoogleCredential from an authorized access_token?


I have an OAuth2 token like this...

{{
  "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in": "3600",
  "refresh_token": "xxxxxxxxxxxxxxxxxx",
  "token_type": "Bearer",
}}

and I'm trying to create a DriveService object...

Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "foo",
});

(like this?)

but I'm clearly not doing this properly and I'm having trouble finding documentation.

When I attempt to create a GoogleCredential to pass to the DriveService

GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);

I get the following exception:

{System.InvalidOperationException: Error creating credential from JSON. Unrecognized credential type .

Am I going about this the wrong way entirely?

(This is the sample code context)


Solution

  • I have managed to figure this out.

    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,
      }
    });
    

    and also a 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"],
    };
    

    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",
    });
    

    I updated the TestXamAuthGoogleDrive test harness project to reflect these changes.