DotNet Google API身份验证问题
问题描述:
我正在尝试为.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能帮帮我吗?
谢谢!
答
我解决了这个问题。我在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
现在我面临的一个问题,但我会创建一个新的话题。
谢谢!