我创建了一个Web应用程序,我已经在其中实现了Google登录。我想为其添加搜索功能,用户可以在其中搜索他/她的驱动器中存在的任何文件。在Google Drive Api的示例代码中,应用程序会打开浏览器窗口,在提供凭据后,令牌会存储在本地,我想通过代码传递凭据,因此我为此创建了一个服务帐户。
在google documentation中,写有Your application now has the authority to make API calls as users in your domain (to "impersonate" users). When you prepare to make authorized API calls, you specify the user to impersonate.
这是我的代码 -
static void Main(string[] args)
{
try
{
var service = AuthenticateServiceAccountV1(GServiceAccount, "keycredentials.json");
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 1000;
listRequest.Fields = "nextPageToken, files(webViewLink, name, id)";
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
Console.WriteLine("Processing...\n");
if (files != null && files.Count > 0)
{
var listfiles = files.Select(x => x.Id).ToList();
Console.WriteLine(files.Count + " records fetched.");
}
else
{
Console.WriteLine("No files found.");
}
Console.ReadLine();
}
catch(Exception ex)
{
throw ex;
}
}
static DriveService AuthenticateServiceAccountV1(string ServiceAccountEmail, string KeyFilePath)
{
try
{
if (string.IsNullOrEmpty(KeyFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(KeyFilePath))
throw new Exception("The service account credentials file does not exist at: " + KeyFilePath);
if (string.IsNullOrEmpty(ServiceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
if (Path.GetExtension(KeyFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(KeyFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes);
}
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
else if (Path.GetExtension(KeyFilePath).ToLower() == ".p12")
{
var certificate = new X509Certificate2(KeyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccountEmail)
{
Scopes = Scopes,
}.FromCertificate(certificate));
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
return null;
}
}
在上面的代码中,我可以在哪里传递假冒用户的电子邮件ID?我正在为我的应用程序使用g-suite帐户。我尝试将credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
替换为credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes).CreateWithUser("userid@gmail.com");
它提供了一个例外
{“错误:\”unauthorized_client \“,说明:\”客户未经授权使用此方法检索访问令牌。\“,Uri:\”\“”}
答案 0 :(得分:0)
{&#34;错误:\&#34; unauthorized_client \&#34;,说明:\&#34;客户未经授权使用此方法检索访问令牌。\&#34;,Uri:\& #34; \&#34;&#34;}
在google开发者控制台中,您创建了一个包含凭据的项目。有两种类型的凭证,它们具有不同的文件,需要使用不同的代码。
您使用的代码用于使用服务帐户进行身份验证。您使用的凭据文件可能适用于Oauth2。转到Google开发者控制台并创建其他凭据类型并下载新文件。
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Analytics service.
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the Drive service.
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
throw new Exception("CreateServiceAccountDriveFailed", ex);
}
}
}