作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目标:生成包含正文内容和附件的草稿电子邮件,并将其放入我当前用户的 GMail 帐户。
环境:ASP.NET Core 3.1
我已经在我的网络应用程序中使用了 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
的调用是一个全新的身份验证请求,它会弹出一个新的浏览器窗口来针对 Google 进行身份验证(这不起作用,因为重定向 url 等)。我已经通过我现有的启动/登录过程对用户进行了身份验证。
GmailService
构造函数要么不接受参数,要么接受
BaseClientService.Initializer
类,它本身采用
Google.Apis.Services.IConfigurableHttpClientInitializer
目的。在上面的示例中,
UserCredential
类实现了这个接口(interface)。如何使用我现有的登录过程的凭据来构建 gmail 服务?或者,有没有一种方法可以做我想做的事情而不必构建
GmailService
实例?
最佳答案
回答:
您需要使用 Google.Apis.Auth.Mvc
对于 Web 服务,如 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.
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.
关于c# - 在 Startup.cs 中使用 .AddGoogle() 时如何在 Web 应用程序中构建 GmailService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62536260/
我是一名优秀的程序员,十分优秀!