googleapis / google-api-dotnet-client

Google APIs Client Library for .NET
https://developers.google.com/api-client-library/dotnet
Apache License 2.0
1.36k stars 525 forks source link

Oauth2 token without a browser #2873

Open juanborre87 opened 1 week ago

juanborre87 commented 1 week ago

Hi, I need help creating code in .net core to generate an Oauth2 token without a browser and be able to use this token to send a request to the route optimization API.

I have investigated and the option I have seen is:

  1. Create a service account in GCP.
  2. Grant permissions to generate tokens (Service Account Token Creator).
  3. Use a Google library to be able to do impersonation or it can be done from a REST call: https://cloud.google.com/docs/authentication/rest#impersonated-sa, here you get the token.

The problem is that I can't find the code or solution for item 3 in .net core.

Greetings.

jskeet commented 1 week ago

Do you actually need to do impersonation, rather than just authenticating as the service account?

The simplest way to use a service account from .NET is to download the service account JSON file, the either set the GOOGLE_APPLICATION_CREDENTIALS environment variable to specify the path, or if you're using one of the modern libraries (e.g. Google.Maps.RouteOptimization.V1 in this case) you can set the path in the client builder - see https://cloud.google.com/dotnet/docs/reference/help/client-configuration#credentialspath-jsoncredentials-or-googlecredential for details.

Note that if your code is running on GCP (e.g. via Cloud Run, or Compute Engine) you should be able to use the default credentials that come from the metadata server, without doing any of this.

jskeet commented 1 week ago

If you do need impersonation, I believe you can do something like:

var credential = GoogleCredential
    .GetApplicationDefault()
    .Impersonate(new ImpersonatedCredential.Initializer(principalToImpersonate));
jskeet commented 1 week ago

(@amanda-tarafa may well have other suggestions when she's online again.)

amanda-tarafa commented 6 days ago

I'm not certain that your 3 steps solve your use case.

This documentation that you linked https://cloud.google.com/docs/authentication/rest#impersonated-sa describes how to have a user impersonate a service accoun. For that you need to have the access token from the user credential to obtain the access token from the service account. For obtaining the access token from the user credential you need a browser.

It seems like you are looking for the contrary, a service account to imperonate a user. That's only possible with domain-wide delegation for Workspace APIs. I'm not sure if the routes optimization API is a Workspace API.

But, @jskeet 's question stands. Do you need impersonation? Or can't you just use the service account to authorize the API call?