Google ML-Engine预测来自C#身份验证问题

时间:2018-05-03 14:13:13

标签: c# google-api gcloud google-oauth2 google-cloud-ml

关注

OAuth example

成功获得持票人令牌,但回复是:

{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/ {projectID}

2 个答案:

答案 0 :(得分:4)

正如克里斯在上面提到的那样,作为对问题的评论,答案是在要求令牌之前证书的范围:

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

答案 1 :(得分:0)

我没有用C#做过这个,但是我在Python中也遇到了类似代码的问题:

# Doesn't work
# creds = GoogleCredentials.from_stream(SERVICE_ACCOUNT_FILE)

在Python中,以下是有效的:

from oauth2client import service_account
creds = service_account.ServiceAccountCredentials.from_json_keyfile_name('key.json', SCOPES)
creds.get_access_token()

在C#中,您似乎会使用ServiceAccountCredentials类。