我正在努力理解服务帐户和授权如何在 Google API 的上下文中运行。
我有一个 Google 帐户,我们称之为 Fred,它创建了一个服务帐户:FredsGDriveService。我与 FredsGDriveService 共享了 Fred's Drive 中的一个文件夹,并设法使用 Google.Apis.Drivev3 API 编写了一些 .Net 代码,以便从此文件夹上传和下载文件。
现在尝试使用最近发布的 Google.Apis.Formsv1 API 对 Google Forms 进行类似操作。
我有一个表单,位于共享云端硬盘文件夹中。该表单还与 FredsGDriveService 共享。在代码中,我使用与以前相同的凭据,并且我相信我已授予服务帐户使用 GoogleForms API 的权限。但是当我尝试获取此表单时出现以下错误。
{ "error": { "code": 401, "message": "Request had invalid authentication credentials.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [ { "message": "Invalid Credentials", "domain": "global",
"reason": "authError", "location": "Authorization", "locationType":
"header" } ], "status": "UNAUTHENTICATED" } }
我的代码如下:
private readonly FormsService _formsService;
private string _credentialsFileName = "emailmanager-416312-8e1ba22c772b.json";
public MyFormsService()
{
var _credentialsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _credentialsFileName);
_formsService = GetFormsService(_credentialsPath);
}
private FormsService GetFormsService(string serviceAccountKeyPath)
{
var credential = GoogleCredential.FromFile(serviceAccountKeyPath)
.CreateScoped(DriveService.Scope.DriveFile + FormsService.Scope.DriveFile + FormsService.Scope.FormsBody);
return new FormsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Dance Addiction Emails",
});
}
public Form GetForm(string formId)
{
// Create a request to get the form with the specified form ID
FormsResource.GetRequest getRequest = _formsService.Forms.Get(formId);
try
{
// Execute the request and retrieve the form
return getRequest.Execute();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while getting the form: {ex.Message}");
return null;
}
}
var google = new MyFormsService();
Console.Write(google.GetForm("xxxxFormIdxxxx"));
我已成功使用类似的代码创建一个单独的表单,然后检索它,尽管我无法通过 Fred 的帐户找到该表单,因此它是在 serviceaccount 的上下文中创建的。
解决这个问题并没有帮助,因为我不理解这里与服务帐户使用和/或 OAuth2 相关的要求。我的用例是,我有一个程序,我将用它来管理我即将到来的日历以及每次创建的日历此日历中的一个新事件,我需要将其添加到此 google 表单中,那么我选择的服务帐户是否正确,或者我应该使用 OAuth2 还是两者都使用!?