简体   繁体   English

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

[英]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).我想使用 Google Cloud 客户端库的.net变体(例如,用于创建新项目的 资源管理器)。
  • I wouldn't like to use neither service account credentials nor ADC.我不想既不使用服务帐户凭据也不使用 ADC。

Can I somehow pass existing OAuth credentials (access token, obtained for appropriate scope) to the client library to authenticate the given user?我能否以某种方式将现有的OAuth凭据(访问令牌,在适当范围内获得)传递给客户端库以对给定用户进行身份验证? (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.简要查看了ProjectsClientBuilder class,但似乎生成了大量内容(也作为文档),这意味着很难找到任何提示。

The following example shows how to authorize the Google cloud resource manager API using Oauth2 for an installed app.以下示例显示如何使用 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"));

Note for a web application the code will be different.请注意,对于 web 应用程序,代码会有所不同。 Web authorization is not the same with the client library. Web 授权与客户端库不一样。 I havent tried to connect any of the cloud apis via web oauth before.我之前没有尝试通过 web oauth 连接任何云 api。

As mentioned above, only thing needed is to initialize Credential property in the project builder prior the Build() .如上所述,唯一需要做的就是在Build()之前在项目构建器中初始化Credential属性。

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:最后新的更简单,直接返回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.

相关问题 Google Cloud - 错误报告客户端库 - Google Cloud - Error Reporting Client Libraries Firebase 云消息传递:app/invalid-credential - 无法获取有效的 Google OAuth2 访问令牌 - Firebase Cloud messaging : app/invalid-credential - failed to fetch a valid Google OAuth2 access token 为什么 Google Oauth2 在通过移动应用程序进行身份验证时拒绝客户端 ID? - Why is Google Oauth2 rejecting client id when authenticating via mobile app? Cloud Storage 无法管理生产中的文件,oauth2:无法获取令牌 - Cloud Storage can't manage files in production, oauth2: cannot fetch token Spring 启动混合形式登录和 oauth2 Google 登录在谷歌云中部署代码时不起作用 - Spring boot mixed form login and oauth2 Google login don't work when deploying the code in Google Cloud firebase中创建的云函数是否可以在不同的google开发者账户中使用? - Can the cloud functions created in firebase be used in different google developer accounts? nHibernate可以用来访问谷歌云SQL服务器吗? - Can nHibernate be used to access google cloud SQL server? 谷歌云中使用的 blob 名称是什么? - What is the blob name used for in google cloud? 如何将我的 nodejs 库包含在 Google Cloud Functions 中 - How to include my nodejs libraries with Google Cloud Functions 尝试在 python 中导入谷歌云库时出现“DefaultCredentialsError” - `DefaultCredentialsError` when attempting to import google cloud libraries in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM