在 Startup.cs 中使用 .AddGoogle() 时如何在 Web 应用程序中构造 GmailService?

How to construct GmailService in web app when using .AddGoogle() in Startup.cs?

目标:生成包含正文内容和附件的电子邮件草稿并将其放入我当前用户的 GMail 帐户中。

环境:ASP.NETCore 3.1

我已经在我的 Web 应用程序中使用 Google 身份验证,并且正在成功请求 Gmail Compose 范围:

services
    .AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; })
    .AddCookie()
    .AddGoogle(options =>
    {
        IConfigurationSection googleAuthSection = Configuration.GetSection("Authentication:Google");
        options.ClientId = googleAuthSection["ClientId"];
        options.ClientSecret = googleAuthSection["ClientSecret"];
        options.Scope.Add(Google.Apis.Gmail.v1.GmailService.Scope.GmailCompose);
    });

从各种在线示例中,我发现生成草稿并将其保存到 gmail 帐户需要执行以下操作:

var draft = new Draft();
draft.Message = new Message();
draft.Message.Payload = new MessagePart { Body = new MessagePartBody { Data = "hello world".ToBase64Url() } };

var clientSecrets = new ClientSecrets
{
    ClientId = _googleAuthSettings.ClientId,
    ClientSecret = _googleAuthSettings.ClientSecret
};
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
    clientSecrets,
    new[] { Google.Apis.Gmail.v1.GmailService.Scope.GmailCompose },
    user.Data.EmailAddress,
    CancellationToken.None);

var gservice = new Google.Apis.Gmail.v1.GmailService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        ApplicationName = "Aeon"
    });

var createRequest = gservice.Users.Drafts.Create(draft, user.Data.EmailAddress);

问题是对 GoogleWebAuthorizationBroker.AuthorizeAsync 的调用是一个全新的身份验证请求,它会弹出一个新的浏览器 window 以针对 Google 进行身份验证(这不起作用,因为重定向网址等等)。我已经通过我现有的 startup/login 流程对用户进行了授权。

两个 GmailService 构造函数要么不带参数,要么这个 BaseClientService.Initializer class 本身带一个 Google.Apis.Services.IConfigurableHttpClientInitializer 对象。在上面的示例中,UserCredential class 实现了这个接口。如何使用我现有的登录过程的凭据来构建 gmail 服务?或者,有没有一种方法可以在不必构建 GmailService 实例的情况下完成我想做的事情?

答案:

您需要对 Web 服务使用 Google.Apis.Auth.Mvc,因为 GoogleWebAuthorizationBroker.AuthorizeAsync 不能用于创建 Web 应用程序的授权流程。

更多信息:

根据 OAuth in Web Applications 上的文档:

After creating a new web application project in your IDE, add the right Google.Apis NuGet package for Drive, YouTube, or the other service you want to use. Then, add the Google.Apis.Auth.MVC package.

该页面还演示了查询 Google API 服务的 ASP.NET MVC 应用程序。

如果您想在网络上部署 GmailService,您需要使用 the Google.Apis.Auth.MVC package 来实现控制器。

也来自 GoogleWebAuthorizationBroker class 的来源:

/// This class is only suitable for client-side use, as it starts a local browser 
/// that requires user interaction.
/// Do not use this class when executing on a web server, or any cases where the 
/// authenticating end-user is not able to do directly interact with a launched 
/// browser.

参考文献: