2015-03-31 88 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

相关问题