c# - 从 C# 桌面应用程序调用谷歌云功能?
解决方案
如果您想从 ac# 桌面应用程序调用经过身份验证的 Cloud Function(CF),这就是您需要做的。
创建自定义 Google 服务帐户。
从以前的服务帐户创建一个密钥 json 文件。
在该过程结束时,您应该有一个密钥 json 文件,dotnet 应用程序将使用该文件对 Cloud Function 进行身份验证。部署一个处理敏感数据的云函数。对于概念验证测试,我使用了返回消息“hello world”的Cloud Functions 快速入门。
在 Cloud Function 中强制执行身份验证。
为此,您需要转到Cloud Functions 主页并勾选 CF 名称左侧的复选框。
然后在屏幕顶部,您需要单击选项权限(将显示右侧面板)。
从角色/成员列表中,展开Cloud Function invoker部分。
删除身份AllUsers
,因为这会使 CF 公开,并且只添加创建的服务帐户的名称。创建 dotnet 本地 Web 应用程序
dotnet new web -o helloworld --no-https
安装Google Auth 库以生成身份令牌。
dotnet add package Google.Apis.Auth --version 1.53.0
在 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");
});
- 这些是我需要在 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;
- 最后执行
dotnet watch run
并看到来自经过身份验证的 Cloud Function(hello world) 的消息打印在本地控制台上。
希望这个对你有帮助
推荐阅读
- java - 玩!框架功能测试幽灵数据
- reactjs - 反应钩子,更新一个状态以响应另一个状态更新
- java - 无法使用 Spring Boot 通过邮递员更新表格内容
- reactjs - ReactJS 通过父更改兄弟状态
- typescript - 子类型与其超类型的交集是否与子类型相同?
- r - 由 coercion 引入的 NAs 由 knn 中的 coercionError 引入
- python - PyQt 自定义小部件不可见
- go - 为什么 Go time.Format 会根据时区返回不同的值?
- vb.net - System.ArgumentException: '已存在具有相同键的条目 | For 循环和 SortedLists
- python - 添加或减去函数会导致无类型错误