MLowijs
MLowijs

Reputation: 1495

Azure AD AcquireToken does not work with app password

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.

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("[email protected]", "my-password"));

The user that is trying to authenticate is a Global Admin in this AD.

Is it even possible to do authentication like this for a user with MFA?

Upvotes: 4

Views: 3665

Answers (1)

MLowijs
MLowijs

Reputation: 1495

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.

By using ServiceErrorCodes.All(), I ensure that only when a single AppPasswordRequired error occurs, authentication has succeeded.

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.

Upvotes: 2

Related Questions