【发布时间】:2021-12-02 17:27:49
【问题描述】:
我想保护一些 Google Cloud Platform HTTP 函数。我一直关注这里:Secure Google Cloud Functions HTTP Trigger With Auth
我已成功按照说明进行操作,并能够使用 Auth 标头的 Add OIDC token 选项以及我为调用这些 HTTP 函数而设置的服务帐户来设置它提到的调度程序作业。函数从调度器调用成功。
(添加IAM会员的过程略有不同,我是按照these instructions)
我可以通过测试功能从 GCP 中成功调用该函数,并且从调度程序成功调用该函数。在没有任何身份验证的情况下调用该函数会导致此消息,因此我相当确定身份验证设置正确:
错误:禁止 您的客户端无权从此服务器获取 URL /myAuthenticatdeFunction。
现在我已经编写了一个 c# 应用程序,它检索 OIDC 令牌并根据指令 here 发出 http 请求。
public async Task<HttpResponseMessage> InvokeRequestAsync(
string iapClientId, string uri, CancellationToken cancellationToken = default)
{
// Get the OidcToken.
// You only need to do this once in your application
// as long as you can keep a reference to the returned OidcToken.
OidcToken oidcToken = await GetOidcTokenAsync(iapClientId, cancellationToken);
// Before making an HTTP request, always obtain the string token from the OIDC token,
// the OIDC token will refresh the string token if it expires.
string token = await oidcToken.GetAccessTokenAsync(cancellationToken);
// Include the OIDC token in an Authorization: Bearer header to
// IAP-secured resource
// Note: Normally you would use an HttpClientFactory to build the httpClient.
// For simplicity we are building the HttpClient directly.
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await httpClient.GetAsync(uri, cancellationToken);
}
/// <summary>
/// Obtains an OIDC token for authentication an IAP request.
/// </summary>
/// <param name="iapClientId">The client ID observed on
/// https://console.cloud.google.com/apis/credentials. </param>
/// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>
/// <returns>The HTTP response message.</returns>
public async Task<OidcToken> GetOidcTokenAsync(string iapClientId, CancellationToken cancellationToken)
{
// Obtain the application default credentials.
//GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(cancellationToken);
string filepath = @"<path to json file for service account>";
GoogleCredential credential = await GoogleCredential.FromFileAsync(filepath, cancellationToken);
// Request an OIDC token for the Cloud IAP-secured client ID.
return await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId), cancellationToken);
}
当我运行它时,这就是我得到的结果:
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>401 Unauthorized</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Unauthorized</h1>
<h2>Your client does not have permission to the requested URL <code>/myAuthenticatdeFunction</code>.</h2>
<h2></h2>
</body></html>
我错过了什么?为什么不认证?
【问题讨论】: