問題描述
我正在嘗試使用 .NET ADAL 庫驗證 Azure AD 中的用戶密碼.這適用于沒有 MFA 的普通用戶帳戶,但我遇到了為已激活 MFA 的用戶執(zhí)行此操作的問題.
I'm trying to verify a user's password in Azure AD using the .NET ADAL library. This works fine for a regular user account without MFA, but I ran into problems doing this for a user who has MFA activated.
當(dāng)使用用戶的實際密碼時,我得到了 AADSTS50076: Application password is required.
,這很公平,但是當(dāng)我創(chuàng)建一個新的應(yīng)用程序密碼時,我收到了錯誤 AADSTS70002: 驗證憑據(jù)時出錯.AADSTS50020:用戶名或密碼無效
.我已經(jīng)創(chuàng)建了多個應(yīng)用密碼,但它們都不起作用.
When using the user's actual password, I got AADSTS50076: Application password is required.
, which is fair enough, but when I then created a new app password, I received the error AADSTS70002: Error validating credentials. AADSTS50020: Invalid username or password
. I've created multiple app passwords but they all do not work.
用于嘗試驗證的代碼如下:
The code used to attempt authentication is as follows:
var ac = new AuthenticationContext("https://login.windows.net/my-tenant.com");
var authResult = ac.AcquireToken("https://graph.windows.net", "my-client-id", new UserCredential("my.account@my-tenant.com", "my-password"));
嘗試進行身份驗證的用戶是此 AD 中的全局管理員.
The user that is trying to authenticate is a Global Admin in this AD.
是否甚至可以為具有 MFA 的用戶進行這樣的身份驗證?
Is it even possible to do authentication like this for a user with MFA?
推薦答案
所以,為了回答我自己的問題,我采取了以下措施(為簡潔起見):
So, to answer my own question somewhat, I resorted to doing the following (cleaned up for brevity):
public class AzureAdAuthenticationProvider
{
private const string AppPasswordRequiredErrorCode = "50076";
private const string AuthorityFormatString = "https://login.windows.net/{0}";
private const string GraphResource = "https://graph.windows.net";
private AuthenticationContext _authContext;
private string _clientId;
public AzureAdAuthenticationProvider()
{
var tenantId = "..."; // Get from configuration
_authContext = new AuthenticationContext(string.Format(AuthorityFormatString, tenantId));
}
public bool Authenticate(string user, string pass)
{
try
{
_authContext.AcquireToken(GraphResource, _clientId, new UserCredential(user, pass));
return true;
}
catch (AdalServiceException ase)
{
return ase.ServiceErrorCodes.All(sec => sec == AppPasswordRequiredErrorCode);
}
catch (Exception)
{
return false; // Probably needs proper handling
}
}
}
它不漂亮,但它可以完成工作.
It's not pretty, but it does the job.
通過使用ServiceErrorCodes.All()
,我保證只有當(dāng)一個AppPasswordRequired錯誤發(fā)生時,認證成功.
By using ServiceErrorCodes.All()
, I ensure that only when a single AppPasswordRequired error occurs, authentication has succeeded.
此方法的唯一缺點是啟用 MFA 的用戶必須使用其實際帳戶密碼才能登錄.似乎不支持使用應(yīng)用密碼.
The only disadvantage to this method, is that a user with MFA enabled has to use their actual account password to login. Using an app password does not seem to be supported.
這篇關(guān)于Azure AD AcquireToken 不適用于應(yīng)用密碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!