gpt4 book ai didi

c# - Google Drive API v3 使用 JSON 而不是 P12(服务帐户)- 意外字符

转载 作者:太空狗 更新时间:2023-10-29 23:13:23 25 4
gpt4 key购买 nike

Error: Unexpected character encountered while parsing value: e. Path '', line 0, position 0.

我正在使用 Google .Net 客户端库来访问 Google Drive API v3 特别是 Google.Apis.Drive.v3包裹。我授权在 C# 中使用“服务帐户”。

用p12 key 授权是没有问题的。但是,建议使用 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可以吗?

最佳答案

这适用于我使用来自 Google Developers Console 的 JSON 凭据文件。我正在使用 Analytics Service,但只是换出 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>",
});
}

关于c# - Google Drive API v3 使用 JSON 而不是 P12(服务帐户)- 意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35744158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com