我正在使用 .NET google 客户端库中的 Google DRIVE API,并希望从服务帐户中模拟用户。我读过许多其他面临同样问题的用户,但没有一个修复对我有用。下面是详细信息。
- 创建服务帐户并启用域范围的委派(现在超过 3 小时)。
- 下载 *.p12 文件并记下密码
- 使用服务帐户客户端 ID 添加了权限驱动范围
- 使用以下代码创建服务并从谷歌驱动器上传/获取数据
代码
var certificate = new X509Certificate2(keyfilepath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
string[] scopes = new string[] {
DriveService.Scope.Drive,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveMetadata
};
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceaccountemail)
{
Scopes = scopes,
User = "abcr@mydomain.com"
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample"
//HttpClientFactory = new ProxySupportedHttpClientFactory()
});
var keyname = "1231312.p12";
var newservicact = "asdfasdf@gsuite-migration-4564654.iam.gserviceaccount.com";
_service = this.AuthorizeServiceAccountwithMimic(newservicact,keyname);
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = System.IO.Path.GetFileName(_uploadFile);
body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
body.Properties = customcolumns;
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
request.SupportsTeamDrives = true;
request.ProgressChanged += Request_ProgressChanged;
request.ResponseReceived += Request_ResponseReceived;
request.Upload();
return request.ResponseBody;
}
在 Request_ProgressChanged 事件中发送的第一批数据时,我遇到了错误。
执行 google API 方法时,它会抛出错误
错误:“unauthorized_client”,描述:“客户端未经授权无法使用此方法检索访问令牌。”,Uri:“”
我已经检查了许多启用 DWD 的论坛和 aaded 应用程序范围......任何人有任何想法请帮助,