Search code examples
c#google-apigcloudgoogle-oauthgoogle-cloud-ml

Google ML-Engine Predict from C# Authentication issue


Followed

OAuth example

successfully getting bearer token, but response is:

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

using a service account with 'ML Engine Developer' Role. Here is the code:

        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();

where googleapiprojecturl = https://ml.googleapis.com/v1/projects/{projectID}


Solution

  • as Chris suggested above, as comment on the question, the answer was scope on the credential before asking for token:

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