Mar*_*cel 5 c# google-api google-drive-api google-api-dotnet-client service-accounts
错误:解析值时遇到意外字符: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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在记事本中查看了JSON文件,它似乎已加密。
“ ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAicmfkaWFudC1tZXJjdXJ5LTEyMjkwNyIsCiAgIn ..........”
可以继续使用P12吗?
确保您正在下载正确的文件...
GoogleCredential.FromStream(stream)
Run Code Online (Sandbox Code Playgroud)
适用于 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": ""
}
Run Code Online (Sandbox Code Playgroud)
您可以通过单击显示客户端 ID 的网格右侧的“下载 JSON”按钮,从https://console.developers.google.com/apis/credentials获取此文件。只需确保所选 ID 的类型为“服务帐户客户端”即可。
| 归档时间: |
|
| 查看次数: |
2778 次 |
| 最近记录: |