Rüd*_*ert 8 c# authentication curl api-key google-cloud-vertex-ai
在 ac# 程序中,我想使用api 密钥调用我的vertex ai 端点进行预测(通过“Google Cloud”/Credentials/API Keys”))。我向 api 密钥授予了对 Vertex AI 的访问权限,并作为测试其他所有内容。
使用curl 或c# 调用它时,我收到错误消息,该服务需要“OAuth 2 访问令牌”或其他内容。
CURL: curl -X POST -H“apikey=..mykey...”-H“内容类型:application/json”https://.....googleapis.com/v1/projects/[PROJECT_ID]/位置/europe-west4/endpoints/[ENDPOINT_ID]:predict -d @image.json
错误: “错误”:{“代码”:401,“消息”:“请求缺少所需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。...}
我的问题: 有没有办法使用 Apikey 对 vertex ai 进行身份验证?
小智 1
我发现这有点旧了,但我遇到了同样的问题,一周后就解决了。
以下是步骤
在 C# 中使用此代码
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
// Define the endpoint URL
var endpointUrl = $"https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint_id}:predict";
// Read the image file as bytes
var imageData = File.ReadAllBytes(filename);
// Convert the image data to base64
var imageBase64 = Convert.ToBase64String(imageData);
// Define the request body
var requestBody = new
{
instances = new[]
{
new {
content = imageBase64
}
}
};
// Serialize the request body to JSON
var requestBodyJson = JsonConvert.SerializeObject(requestBody);
// Create an HTTP client and request message
using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Post, endpointUrl);
request.Content = new StringContent(requestBodyJson, System.Text.Encoding.UTF8, "application/json");
// Set the authentication header
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_ACCESS_TOKEN");
// Send the request and get the response
using var response = await client.SendAsync(request);
var responseBodyJson = await response.Content.ReadAsStringAsync();
// Deserialize the response body from JSON
dynamic responseBody = JsonConvert.DeserializeObject(responseBodyJson);
// Process the response
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说,邮件问题是 YOUR_ACCESS_TOKEN,它不是 API 密钥。
o 获取用于调用 Vertex AI 端点的访问令牌,您需要使用具有调用端点所需权限的 Google Cloud 凭证进行身份验证。
以下是使用 Google Cloud SDK 获取访问令牌的方法:
按照此处的说明安装 Google Cloud SDK:https: //cloud.google.com/sdk/install。
打开终端或命令提示符并运行以下命令以使用您的 Google Cloud 凭据进行身份验证:
gcloud auth application-default login
Run Code Online (Sandbox Code Playgroud)
按照提示登录您的 Google Cloud 帐户并授予 Google Cloud SDK 权限。
通过身份验证后,您可以通过运行以下命令获取访问令牌:
gcloud auth application-default print-access-token
Run Code Online (Sandbox Code Playgroud)
这将输出一个访问令牌,您可以使用该令牌来验证您对 Vertex AI 端点的请求。
在我之前提供的示例代码片段中,将 YOUR_ACCESS_TOKEN 替换为您使用上述步骤获得的访问令牌。
那应该可以解决它
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |