首页 > 解决方案 > 从 C# 桌面应用程序调用谷歌云功能?

问题描述

我的代码中有一些敏感信息,我 在此处输入图像描述 想创建一个返回敏感信息的云函数。有什么方法可以调用云函数并从 C# 桌面应用程序接收数据?

标签: c#google-cloud-functions

解决方案


如果您想从 ac# 桌面应用程序调用经过身份验证的 Cloud Function(CF),这就是您需要做的。

  1. 创建自定义 Google 服务帐户。

  2. 从以前的服务帐户创建一个密钥 json 文件。
    在该过程结束时,您应该有一个密钥 json 文件,dotnet 应用程序将使用该文件对 Cloud Function 进行身份验证。

  3. 部署一个处理敏感数据的云函数。对于概念验证测试,我使用了返回消息“hello world”的Cloud Functions 快速入门。

  4. 在 Cloud Function 中强制执行身份验证。
    为此,您需要转到Cloud Functions 主页并勾选 CF 名称左侧的复选框。
    然后在屏幕顶部,您需要单击选项权限(将显示右侧面板)。
    从角色/成员列表中,展开Cloud Function invoker部分。
    删除身份AllUsers,因为这会使 CF 公开,并且只添加创建的服务帐户的名称。

  5. 创建 dotnet 本地 Web 应用程序
    dotnet new web -o helloworld --no-https

  6. 安装Google Auth 库以生成身份令牌。
    dotnet add package Google.Apis.Auth --version 1.53.0

  7. 在 Startup.cs 中包含以下代码,以调用经过身份验证的 Cloud Function。

endpoints.MapGet("/", async context =>
    Console.WriteLine("Program starting");    
    //Creating identity token from service account key json file of step 2
    //The key json file is located in the same folder that the Startup.cs
    GoogleCredential credential = GoogleCredential.FromFile("[FILENAME].json");
    var audience= "[CLOUD_FUNCTION_URL]";
    var token = await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(audience), CancellationToken.None);
    String bt = await token.GetAccessTokenAsync(CancellationToken.None);

    //Create http client to send web request
    HttpClient hc = new HttpClient
    hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",bt);
    HttpResponseMessage hr = await hc.GetAsync("[CLOUD_FUNCTION_URL]");
    string responseBody = await hr.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
    await context.Response.WriteAsync("Program completed");
});
  1. 这些是我需要在 Startup.cs 文件顶部导入的库。
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Google.Apis.Auth.OAuth2;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
  1. 最后执行dotnet watch run并看到来自经过身份验证的 Cloud Function(hello world) 的消息打印在本地控制台上。

希望这个对你有帮助


推荐阅读