2015-03-31 48 views
4

我正嘗試使用.NET ADAL庫在Azure AD中驗證用戶的密碼。 這適用於沒有MFA的普通用戶帳戶,但我遇到了這樣的問題,對於啓用了MFA的用戶而言,Azure AD AcquireToken不適用於應用程序密碼

使用用戶的實際密碼時,我得到了AADSTS50076: Application password is required.,這很公平,但是當我創建新的應用程序密碼時,收到錯誤AADSTS70002: Error validating credentials. AADSTS50020: Invalid username or password。我創建了多個應用程序密碼,但它們都不起作用。

用於嘗試認證所述代碼如下:

var ac = new AuthenticationContext("https://login.windows.net/my-tenant.com"); 
var authResult = ac.AcquireToken("https://graph.windows.net", "my-client-id", new UserCredential("[email protected]", "my-password")); 

被嘗試驗證用戶是全球管理員在該AD。

對於使用MFA的用戶,是否可以像這樣進行認證?

+0

這是不可能的,因爲MFA需要用戶交互。 – 2015-03-31 12:51:07

+0

這不就是應用程序的密碼是什麼,能夠登錄到無法通過MFA登錄的內容?例如,我創建了用於在智能手機/ Outlook上登錄Office 365的應用程序。此外,該錯誤消息明確說我應該創建一個應用程序密碼進行身份驗證。 – MLowijs 2015-03-31 13:18:30

+0

是的,正如你在你的問題中指出的那樣,對於未配置爲MFA的用戶來說,它工作正常。 – 2015-03-31 13:27:27

回答

2

因此,要回答我的問題有點,我使出執行以下操作(清理爲了簡潔):

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 
     } 
    } 
} 

這不是很漂亮,但它的工作。

通過使用ServiceErrorCodes.All(),我確保只有當發生單個AppPasswordRequired錯誤時,驗證成功。

此方法的唯一缺點是啓用了MFA的用戶必須使用其實際帳戶密碼才能登錄。使用應用密碼似乎不被支持。

+0

我希望能夠重現這一點。這個類如何與固定的Startup類掛鉤?另外,IAuthenticationProvider在哪裏定義(IoC是你的)? – GaTechThomas 2015-07-31 15:16:07

+0

我不知道;我沒有將這與Startup類結合使用。 IAuthenticationProvider是我的,爲清楚起見,刪除它。 – MLowijs 2015-08-04 20:59:58

相關問題