2017-05-04 97 views
0

我正在嘗試爲.Net(VB.Net)運行Google Prediction API,但我遇到了一些問題。 有人有使用服務帳戶密鑰驗證的代碼示例?DotNet Google API身份驗證問題

我的代碼:

Dim myService As New PredictionService() 
Dim myInput As New Data.Input() 
Dim myInputData As New Data.Input.InputData() 
Dim myListParameters As New List(Of Object) 

myListParameters.Add("myInfo") 
myInputData.CsvInstance = myListParameters 
myInput.InputValue = myInputData 

Dim myRequest As TrainedmodelsResource.PredictRequest = _ 
myService.Trainedmodels.Predict(myInput, "myProject", "myModel") 

myRequest.OauthToken = "How can I get the OauthToken?" 
myRequest.Key = "My API Key" 

Dim myResponse = myRequest.Execute() 

當我運行上面的代碼中,我得到的迴應:

Google.Apis.Requests.RequestError 
Login Required [401] 
Errors [ 
    Message[Login Required] Location[Authorization - header] Reason[required] Domain[global] 
] 

那麼,在谷歌控制檯我創建了一個服務帳戶的關鍵,我做的JSON下載文件,並嘗試執行代碼下面生成authToken

Dim prediction As New PredictionService 
Dim service = ServiceAccountCredential.FromServiceAccountData(_ 
New StreamReader("the path of jsonFile").BaseStream) 
Dim auth As String = Await service.GetAccessTokenForRequestAsync() 

當我運行此代碼時,得到th E錯誤: 「invalid_scope」,「空或丟失的範圍不允許的。」烏里:「」從我的變量服務

範圍屬性是空的,它是隻讀的。所以我不知道如何繼續。

Someboby能幫幫我嗎?

謝謝!

回答

0

我解決了這個問題。我在Google控制檯上創建了一個新的服務帳戶密鑰,但現在使用P12代替JsonFile。

下面的代碼:

Private Async Function GetToken() As Task(Of String) 

    Dim service_email = "your e-mail service accout [email protected]" 

    Dim certificate As New X509Certificate2("yourCertificatePath.p12", "notasecret", X509KeyStorageFlags.Exportable) 

    Dim credential As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(service_email) With { 
     .Scopes = New String() {"https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/prediction"} 
    }.FromCertificate(certificate)) 

    credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait() 

    Return credential.Token.AccessToken 

End Function 

現在我面臨的一個問題,但我會創建一個新的話題。

謝謝!