dan
dan

Reputation: 245

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)

Upvotes: 5

Views: 7275

Answers (2)

Alex P.
Alex P.

Reputation: 1158

Working example at:

https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#installed-applications

The code will present the end user with an authorization page - where you have to log in with your google account and authorize the application to use the respective Google Service.

Upvotes: 0

dan
dan

Reputation: 245

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.

Upvotes: 7

Related Questions