c# - Google ML-Engine Predict from C# 身份验证问题

标签 c# google-api gcloud google-oauth google-cloud-ml

关注

OAuth example

成功获取不记名 token ,但响应是:

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Vary: X-Origin
  Vary: Referer
  Vary: Origin
  Vary: Accept-Encoding
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
  X-Content-Type-Options: nosniff
  Alt-Svc: hq=":443"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="43,42,41,39,35"
  Transfer-Encoding: chunked
  Accept-Ranges: none
  Cache-Control: private
  Date: Thu, 03 May 2018 13:29:53 GMT
  Server: ESF
  WWW-Authenticate: Bearer realm="https://accounts.google.com/"
  Content-Type: application/json; charset=UTF-8
}}

使用具有“ML Engine Developer”角色的服务帐户。 这是代码:

        var url = $"{googleapiprojecturl}/models/{modelname}/versions/{version}:predict";
        GoogleCredential credential;
        using (Stream stream = new FileStream(@"C:\serviceacctkey.json", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = GoogleCredential.FromStream(stream);
        }
        var bearer_token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync(url);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token);
        var content = new StringContent(payloadJsonString, Encoding.UTF8, "application/json");
        var responseMessage = await client.PostAsync(url, content);
        responseMessage.EnsureSuccessStatusCode();

其中 googleapiprojecturl = https://ml.googleapis.com/v1/projects/ {项目ID}

最佳答案

正如克里斯在上面所建议的那样,作为对问题的评论,答案是在请求 token 之前的凭证范围:

credential = GoogleCredential.FromStream(stream).CreateScoped(new[] { CloudMachineLearningEngineService.Scope.CloudPlatform });

关于c# - Google ML-Engine Predict from C# 身份验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157193/

相关文章:

google-cloud-platform - 无法在 Google Cloud Platform 中将我的 E2 实例编辑为 N1 实例

c# - Datagridview 完全加载时显示 Windows 窗体

c# - Windows Phone 7 下的脚本库

python - 使用 google-api-python-client 授予 GAE 应用对 Google API 的访问权限

google-api - 即使在服务器到服务器身份验证后也无法使用 Google Play Developer API

gcloud - 谷歌CP : assign/remove ephemeral IP to an existing instance

c# - 基于等待任务的队列

c# - sharpNLP 作为 .nbin 文件扩展名

javascript - 无法使用 Google 距离矩阵读取未定义的属性 'text'

cron - 需要在 Google 计算引擎 (gce) 上运行 cron 作业,以使用服务帐户执行 gcloud 快照