MailKit、Office 365 和 OAUTH2:服务器端应用程序身份验证问题

问题描述 投票:0回答:1

我必须构建一个在服务器端批量运行的 .Net 控制台应用程序,并使用 Office365 和 MailKit 向收件人发送电子邮件。

我公司最近推出了多重身份验证;我已经重写了一个交互式应用程序,允许用户使用 MailKit 和 MFA 发送电子邮件,但我无法在无人值守的应用程序中实现相同的功能。

我已经在 Microsoft Azure 上注册应用程序,创建客户端密钥并实现以下类:

    public class Mailer {
    public async static void Send(string subject, string body) {
        string tenantID = "abcdef";
        string clientId = "ghilmn";
        string clientSecret = "opqrst";
        string appName = "MyApp";

        //clientSecret = Uri.EscapeDataString(clientSecret);
        //clientSecret = Uri.EscapeUriString(clientSecret);

        var MyConfidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithTenantId(tenantID)
            .Build();

        var scopes = new string[] {"https://graph.microsoft.com/.default"};

        try {
            var authToken = await MyConfidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

            var oauth2 = new SaslMechanismOAuth2(appName, authToken.AccessToken);  //  SaslMechanismOAuth2(appName, authToken.AccessToken);
            var m_client = new SmtpClient(new ProtocolLogger("smtp.log"));
            await m_client.ConnectAsync("outlook.office365.com", 587, SecureSocketOptions.StartTls);
            await m_client.AuthenticateAsync(oauth2);
        }
        catch (Exception ex) {
            Debug.WriteLine(ex.Message);
            // do nothing;
        }
        return;

    }

虽然令牌似乎已正确获取(authToken.AccessToken 不为空),但

等待 m_client.AuthenticateAsync(oauth2);

产生以下错误:

Eccezione generata: 'MailKit.Security.AuthenticationException' in System.Private.CoreLib.dll
535: 5.7.3 Authentication unsuccessful [ZR0P278CA0036.CHEP278.PROD.OUTLOOK.COM]

基本上看不懂

  • 如果 SaslMechanismOAuth2 是要调用的正确选项
  • 如果是,我应该将什么 userName 传递给 oauth2 的构造函数;我尝试使用 AppName、AppID 甚至用户电子邮件,但没有成功。

任何提示将不胜感激,提前致谢。

保罗

P.S. 正在运行的交互式应用程序使用 PublicClientApplicationBuilder 和 AcquireTokenInteractive 调用,使用以下代码。

        public async Task  Connect_MFA() {
        
        var options = new PublicClientApplicationOptions {
            ClientId = "abcd",
            TenantId = "efgh",
            RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
        };

        var publicClientApplication = PublicClientApplicationBuilder
            .CreateWithApplicationOptions(options)
            .Build();

        var scopes = new string[] {
            "email",
            "offline_access",
            //"https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
            //"https://outlook.office.com/POP.AccessAsUser.All",  // Only needed for POP
            "https://outlook.office.com/SMTP.Send", // Only needed for SMTP
        };

        var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();

        var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);

        m_client = new SmtpClient(new ProtocolLogger("smtp.log"));
        await m_client.ConnectAsync("outlook.office365.com", 587, SecureSocketOptions.StartTls);
        await m_client.AuthenticateAsync(oauth2);
    }
c# oauth-2.0 office365 mailkit
1个回答
0
投票

回复晚了,但我希望这可以节省我花在研究这个问题上的一周时间。

最简单/最好的答案是使用 Microsoft.Graph。看看这个: https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=csharp

© www.soinside.com 2019 - 2024. All rights reserved.