错误:解析值时遇到意外的字符:e。路径 '',第0行,第0位。
我正在使用Google .Net客户端库来访问Google驱动器API v3,特别是Google.Apis.Drive.v3包。我正在授权使用C#的“服务帐户”。
使用p12密钥进行授权是没有问题的。但是,建议使用JSON并保持p12格式以便向后兼容。
我从Google Developers Console下载了JSON文件,并尝试使用以下代码进行授权:
public static Google.Apis.Drive.v3.DriveService AuthenticateServiceAccountJSON(string keyFilePath) {
// check the file exists
if (!File.Exists(keyFilePath)) {
Console.WriteLine("An Error occurred - Key file does not exist");
return null;
}
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata, // view and manage its own configuration data
DriveService.Scope.DriveFile, // view and manage files created by this app
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts }; // modify your app scripts
try {
using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read)) {
var credential = GoogleCredential.FromStream(stream);
if (credential.IsCreateScopedRequired) {
credential.CreateScoped(scopes);
}
// Create the service.
Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = "MyDrive",
});
return service;
}
} catch (Exception ex) {
Console.WriteLine(ex.InnerException);
return null;
}
}
我查看了记事本中的JSON文件,似乎已加密。
“ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAicmFkaWFudC1tZXJjdXJ5LTEyMjkwNyIsCiAgIn ..........”
继续使用P12可以吗?
答案 0 :(得分:3)
这适用于我使用Google Developers Console中的JSON凭据文件。我正在使用Google Analytics服务,但只需替换Drive服务的相应名称:
private AnalyticsReportingService service;
public async Task GetAuthorizationByServiceAccount()
{
string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // Put your scopes here
var keyFilePath = AppContext.BaseDirectory + @"KeyFile.json";
//Console.WriteLine("Key File: " + keyFilePath);
var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read);
var credential = GoogleCredential.FromStream(stream);
credential = credential.CreateScoped(scopes);
service = new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "<Your App Name here>",
});
}
答案 1 :(得分:1)
确保您正在下载正确的文件......
GoogleCredential.FromStream(stream)
适用于JSON文件。它应该看起来像这样:
{
"type": "service_account",
"project_id": "",
"private_key_id": "",
"private_key": "-----BEGIN PRIVATE KEY-----
---END PRIVATE KEY-----\n",
"client_email": "",
"client_id": "",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": ""
}
您可以通过单击显示客户端ID的网格右侧的“下载JSON”按钮,在https://console.developers.google.com/apis/credentials获取此文件。只需确保所选ID的类型为&#34;服务帐户客户端&#34;。