繁体   English   中英

OAuth2 可以在 Google Cloud 客户端库中使用吗?

[英]Can OAuth2 be used in Google Cloud Client Libraries?

  • 我想使用 Google Cloud 客户端库的.net变体(例如,用于创建新项目的 资源管理器)。
  • 我不想既不使用服务帐户凭据也不使用 ADC。

我能否以某种方式将现有的OAuth凭据(访问令牌,在适当范围内获得)传递给客户端库以对给定用户进行身份验证? (或者)我需要任何身份验证客户端库吗?

简要查看了ProjectsClientBuilder class,但似乎生成了大量内容(也作为文档),这意味着很难找到任何提示。

以下示例显示如何使用 Oauth2 为已安装的应用程序授权Google 云资源管理器API。

// 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"));

请注意,对于 web 应用程序,代码会有所不同。 Web 授权与客户端库不一样。 我之前没有尝试通过 web oauth 连接任何云 api。

如上所述,唯一需要做的就是在Build()之前在项目构建器中初始化Credential属性。

只是为了完整性:

    // 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;
        }
    }

最后新的更简单,直接返回token,不需要修改request本身:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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