我正在尝试为.Net(VB.Net)运行Google Prediction 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()
当我运行此代码时,得到错误: “invalid_scope”,“空格或缺少范围不允许。”,Uri:“”
我的变量服务的Scope属性为Empty,它是ReadOnly。所以我不知道如何继续。
Someboby可以帮助我吗?
谢谢!
答案 0 :(得分:1)
我解决了这个问题。我在Google Console上创建了一个新的服务帐户密钥,但现在使用P12而不是JsonFile。
以下是代码:
Private Async Function GetToken() As Task(Of String)
Dim service_email = "your e-mail service accout xxxxx@xxxxx.iam.gserviceaccount.com"
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
现在我面临另一个问题,但我会创建一个新话题。
谢谢!