I want to authenticate my vb.net Winform application to access my Google drive account. It works fine if I use a json file. But I want to avoid having a plain json file lying around the file system with my private keys in it. Especially when I am going to install the application on another machine.
So I tried to hardcode the credential parameters, with no luck so far. This is what I have tried:
Public Function Authenticate() As DriveService
Dim scope As String = DriveService.Scope.Drive
Dim credential As GoogleCredential
Dim params As New JsonCredentialParameters
With params
.Type = JsonCredentialParameters.ServiceAccountCredentialType
.ProjectId = "myprojid"
.PrivateKeyId = "mykeyid"
.PrivateKey = "-----BEGIN PRIVATE KEY-----\n myprivatekey =\n-----END PRIVATE KEY-----\n"
.ClientEmail = "[email protected]"
.ClientId = "12345"
End With
credential = GoogleCredential.FromJsonParameters(params).CreateScoped(scope)
Return New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = "GoogleDriveDownloader"})
End Function
and also this similar approach:
Public Function CreateServiceCredentials() As GoogleCredential
Dim parameters = New JsonCredentialParameters With {
.Type = JsonCredentialParameters.ServiceAccountCredentialType,
.ProjectId = "myprojid",
.PrivateKeyId = "mykeyid",
.PrivateKey = "-----BEGIN PRIVATE KEY-----\n myprivatekey =\n-----END PRIVATE KEY-----\n",
.ClientEmail = "[email protected]",
.ClientId = "12345"
}
Dim json As String = JsonConvert.SerializeObject(parameters)
Dim stream = New MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))
Return GoogleCredential.FromStream(stream)
End Function
In both cases I get the error: ArgumentException: PKCS8 data must be contained within '-----BEGIN PRIVATE KEY-----' and '-----END PRIVATE KEY-----'. Arg_ParamName_Name
If I remove the trailing \n I get the error: FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
What am I doing wrong?
CodePudding user response:
I found it out myself, or let's call it a workaround for it:
I just took the whole text of the json file, put it into a winforms textbox and called:
credential = GoogleCredential.FromJson(txt_Credentials.Text).CreateScoped(scope)
Meh, it works ;-)