作为服务帐户进行身份验证是我需要的方法。
Google SDK 的行为完全具有误导性。当我提供一些不正确的值时,它会退回到基于用户的身份验证(自动打开 Web 浏览器以请求交互式凭据)。我错误地将此解释为表示服务帐户功能是作为由特定交互式用户或类似用户批准并在其上下文中实施的长期密钥。
不需要用户交互,但是需要 .p12 证书,而不是默认 .json 文件提供的任何凭据(我曾尝试以多种方式使用)。这是我使用的代码:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Http;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using GData = Google.Apis.Drive.v2.Data;
public class Drive
{
private const string GoogleDocMimeType = "application/vnd.google-apps.document";
/// <summary>
/// Creates a drive service, authenticated using information found in the Google Developers Console under "APIs & auth / Credentials / OAuth / Service account"
/// </summary>
/// <param name="svcEmail">The service account "Email address"</param>
/// <param name="certPath">The path to the service account "P12 key" file</param>
public Drive(string svcEmail, string certPath)
{
Service = AuthenticateService(svcEmail, certPath);
}
private DriveService Service
{
get;
set;
}
/// <summary>
/// Creates a "Google Doc" and shares it with anyone with the link
/// </summary>
/// <param name="title"></param>
/// <returns>The drive FileId, accessible at https://docs.google.com/document/d/FileId </returns>
public async Task<string> CreateShared(string title)
{
var fileId = await CreateDocument(title);
await ShareFile(fileId);
return fileId;
}
private async Task<string> CreateDocument(string title)
{
var file = new GData.File
{
Title = title,
MimeType = GoogleDocMimeType
};
file = await Service.Files.Insert(file).ExecuteAsync();
return file.Id;
}
private async Task ShareFile(string fileId)
{
Permission permission = new Permission
{
Type = "anyone",
Role = "writer",
WithLink = true
};
var a = Service.Permissions.Insert(permission, fileId);
await a.ExecuteAsync();
}
private static DriveService AuthenticateService(string svcEmail, string certPath)
{
string[] scopes = new[] { DriveService.Scope.DriveFile };
X509Certificate2 certificate = new X509Certificate2(certPath, "notasecret", X509KeyStorageFlags.Exportable);
var init = new ServiceAccountCredential.Initializer(svcEmail) { Scopes = scopes };
IConfigurableHttpClientInitializer credential = new ServiceAccountCredential(init.FromCertificate(certificate));
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Document Management Service",
});
}
}
这是一个实验性消费者:
internal class Program
{
private const string svcEmail = "serviceaccountid@developer.gserviceaccount.com";
private const string certPath = @"credentials\projectname-fingerprintprefix.p12";
private readonly static Drive drive = new Drive(svcEmail, certPath);
private static void Main(string[] args)
{
string id = drive.CreateShared("my title").Result;
Console.WriteLine(id);
}
}
这似乎在隔离的、特定于应用程序/项目的数据存储库中使用 Google 云端硬盘存储空间。根据其他帖子,没有办法获得交互式 Drive UI 视图。我不知道它是否使用了我的个人存储配额等。但是,这是我迄今为止最好的方法,接下来我会自己回答这些问题(不在这里)。