不幸的是,我有一个连接到 exchange web 服务的 azure 函数,所使用的服务帐户启用了 MFA

I have an azure functions that connect to exchange web service unfortunately the service account used has MFA enabled

我正在寻找没有交互式登录的解决方案,但到目前为止我找到的所有解决方案都有。有人可以指出如何在不使用交互式方法的情况下为启用 MFA 的帐户获取访问令牌吗?

这是我的代码:

string clientId = "CLIENTID";
string tenantID = "TENANTID";

string authority = $"https://login.microsoftonline.com/{tenantID}";
string[] scopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };
string username ="USERNAME";
string password = "PASSWORD";
Microsoft.Identity.Client.IPublicClientApplication app;
app = Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(clientId)
                                              .WithAuthority(authority)
                                              .Build();
var securePassword = new SecureString();
Dictionary<string, string> mfa = new Dictionary<string, string>();
mfa.Add("amr_values", "mfa");
foreach (char c in password)        // you should fetch the password keystroke
            securePassword.AppendChar(c);  // by keystroke

var result = app.AcquireTokenByUsernamePassword(scopes,
                username, securePassword)
                .WithExtraQueryParameters(mfa)
                .ExecuteAsync().Result;

我收到这个错误:

MsalUiRequiredException: AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000002-0000-0ff1-ce00-000000000000'.

这是 Azure AD 上的日志:

User did not pass the MFA challenge (non interactive).

如果为用户启用了 MFA,则您无法直接使用 OAuth 2.0 Resource Owner Password Credentials 获取令牌。

但是,有一个可选的解决方法。您可以使用刷新令牌获取新令牌:Refresh the access token

通过这种方式,您无需任何交互即可获得新的令牌。我看到您愿意在您的应用程序中使用密码,因此存储和检索刷新对您来说应该没问题。

Note: As refresh token could be used to acquire a new token, so you need to keep the refresh token at a safe place.