Hello Team,
I want to know the easiest possible code to handle 2 factor authentication using user credentials in my MVC Web App.
Currently I have registered the app as a native app on azure portal as I need to authenticate using username and password.
I am using the AAD CLient Graph Library and ADAL for authentication.Please find the below code for your reference.
public async Task<string> AuthenticateAADUser(string UserName, string Password)
{
try
{
return await GetAppTokenAsync(UserName, Password);
}
catch (AdalException ex)
{
var errorCode = ((Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException)(ex)).ErrorCode;
if(errorCode == "invalid_grant")
{
loginStatus = "Invalid Username or Password";
}
else
{
loginStatus = "Invalid Active Directory Settings";
}
return string.Empty;
}
}
private static async Task<string> GetAppTokenAsync(string UserName, string Password)
{
string clientID = ConfigurationManager.AppSettings["AADAppID"];
string authString = ConfigurationManager.AppSettings["AADAuthURL"];
string resAzureGraphAPI = ConfigurationManager.AppSettings["AADGraphAPI"];
// Instantiate an AuthenticationContext for my directory (see authString above).
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
authenticationContext.TokenCache.Clear();
//UserPasswordCredential credentials = new UserPasswordCredential("ashish@ohmintl.com","mypass@1950");
UserPasswordCredential credentials = new UserPasswordCredential(UserName, Password);
// Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
// using the Username and Password as credentials.
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientID, credentials);
// Return the access token.
return authenticationResult.AccessToken;
}
This code works fine but throws an exception "User Interaction required" when 2 Factor Authentication is enabled on the user.I have searched every possible microsoft blog but didnt find any concrete solution. Please if anybody can help as I need to deliver it urgently.