我正在尝试将文件上传到Google云端硬盘。为此,我有一个启用了域范围权限的服务帐户。 “@xyx.com
”是我的域名。我有一个常见的“abc@xyz.com
”谷歌硬盘。
Google服务帐户为“xxx@xxxx.iam.gserviceaccount.com
”。我需要将文件上传到“abc@xyz.com
”。我试图冒充“abc@xyz.com
”到服务帐户。
以下是我的代码
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
{
// check the file exists
if (!File.Exists(keyFilePath))
{
return null;
}
//Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes
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.DriveMetadata,
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DrivePhotosReadonly,
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts }; // modify your app scripts
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
try
{
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes,
User = "abc@xyz.com",
}.FromCertificate(certificate));
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "CIM_GD_UPLOAD",
});
return service;
}
catch (Exception ex)
{
throw ex;
}
}
我收到以下错误。
Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method.", Uri:""
我正在使用 google api v3 。
请帮助我,是否可以冒充用户帐户到服务帐户?或指导我从谷歌硬盘上传/检索文件的正确方法。
答案 0 :(得分:0)
参考Google Drive API Authorization,您需要使用OAuth 2.0授权请求才能访问Google API。授权过程的第一步是从Google API Console获取OAuth 2.0凭据。当您使用服务帐户时,您必须生成服务帐户凭据,然后delegate domain-wide authority to the service account。
您可能需要按照此documentation:
中的说明进行尝试如果您已授予对服务帐户的域范围访问权限并且您要模拟用户帐户,请使用
setServiceAccountUser
工厂的GoogleCredential
方法指定用户帐户的电子邮件地址。例如:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
.setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
.setServiceAccountUser("user@example.com")
.build();
使用
GoogleCredential
对象在您的应用中调用Google API。