简体   繁体   中英

Can OAuth2 be used in Google Cloud Client Libraries?

  • I would like to use .net variant of Google Cloud Client Libraries ( Resource Manager for creating new project, for example).
  • I wouldn't like to use neither service account credentials nor ADC.

Can I somehow pass existing OAuth credentials (access token, obtained for appropriate scope) to the client library to authenticate the given user? (Or) do I need any authentication client library?

Briefly looked at the ProjectsClientBuilder class, but seems heavy generated (also as the documentation ), meaning it's a bit harder to find any hint.

The following example shows how to authorize the Google cloud resource manager API using Oauth2 for an installed app.

// Key file from google developer console (INSTALLED APP)
var PathToInstalledKeyFile = @"C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json";

// scope of authorization needed for the method in question.
var scopes = "https://www.googleapis.com/auth/cloud-platform";

// Installed app authorizaton.
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(PathToInstalledKeyFile).Secrets,
    new []{  scopes },
    "userName",
    CancellationToken.None,
    new FileDataStore("usercreds", true)).Result;

var client = new ProjectsClientBuilder()
{
    Credential = credential,
}.Build();

var projects = client.ListProjects(new FolderName("123"));

Note for a web application the code will be different. Web authorization is not the same with the client library. I havent tried to connect any of the cloud apis via web oauth before.

As mentioned above, only thing needed is to initialize Credential property in the project builder prior the Build() .

Just for the completeness:

    // when using Google.Apis.CloudResourceManager.v3
    public class Program
    {
        private static async Task OlderMethod(string oAuthToken)
        {
            using var service = new CloudResourceManagerService();

            var id = Guid.NewGuid().ToString("N")[..8];
            var project = new Google.Apis.CloudResourceManager.v3.Data.Project
            {
                DisplayName = $"Prog Created {id}",
                ProjectId = $"prog-created-{id}",
            };
            var createRequest = service.Projects.Create(project);
            createRequest.Credential = new OlderCredential(oAuthToken);

            var operation = await createRequest.ExecuteAsync();
            // ...
        }
    }

    public class OlderCredential : IHttpExecuteInterceptor
    {
        private readonly string oAuthToken;

        public OlderCredential(string oAuthToken) { this.oAuthToken = oAuthToken; }

        public Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", oAuthToken);

            return Task.CompletedTask;
        }
    }

In the end the newer one is simpler, just returning the token, no need to modify the request itself:

    // when using Google.Cloud.ResourceManager.V3
    public class Program
    {
        private static async Task NewerMethod(string oAuthToken)
        {
            var client = await new ProjectsClientBuilder
            {
                Credential = new NewerCredential(oAuthToken),
            }.BuildAsync();

            var id = Guid.NewGuid().ToString("N")[..8];
            var project = new Project
            {
                DisplayName = $"Prog Created New {id}",
                ProjectId = $"prog-created-new-{id}",
            };

            var operation = await client.CreateProjectAsync(project);
        }
    }

    public class NewerCredential : ICredential
    {
        private readonly string oAuthToken;

        public NewerCredential(string oAuthToken) { this.oAuthToken = oAuthToken; }

        public void Initialize(ConfigurableHttpClient httpClient) { }

        public Task<string> GetAccessTokenForRequestAsync(string? authUri, CancellationToken cancellationToken) => Task.FromResult(oAuthToken);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM