You can fetch a user’s last good login date and number of failed login attempts from the AD server. First, you will need these keys in your
We will store the login attempts:
public void StoreLoginAttempts(string userName)
{
string adServer = GetConfigAppSettings("AD_DomainIP");
string adServerUser = GetConfigAppSettings("AD_User");
string adServerPassword = GetConfigAppSettings("AD_Pass");
string adServerContainer = GetConfigAppSettings("AD_Container");
// looks like this: "CN=Users,DC=AD,DC=MyDomain,DC=org"
if (!string.IsNullOrEmpty(adServer)
&& !string.IsNullOrEmpty(adServerUser)
&& !string.IsNullOrEmpty(adServerPassword)
&& !string.IsNullOrEmpty(adServerContainer))
{
PrincipalContext principalContext =
new PrincipalContext
(ContextType.Domain,adServer,adServerContainer,adServerUser,adServerPassword);
UserPrincipal user =
UserPrincipal.FindByIdentity(principalContext, userName);
int numberOfFailedLoginAttempts = user.BadLogonCount;
DateTime? lastSuccessfulLogin = null;
if (user.LastLogon != null)
{
lastSuccessfulLogin = user.LastLogon.Value.ToLocalTime();
}
// save to session
storeSetSession("NumberOfFailedLoginAttempts",
numberOfFailedLoginAttempts.ToString());
SetSession("LastSuccessfulLogin", lastSuccessfulLogin.ToString());
}
}
You can fetch the login attempts and last login by getting the session object. For example, you can use a code block like this in your code to populate the login attempts message in your app’s header or footer:
private string GetLoginAttemptsMessage()
{
// get values from session saved during LogOn
string numberOfFailedLoginAttempts = GetSession("NumberOfFailedLoginAttempts");
string lastSuccessfulLogin = GetSession("LastSuccessfulLogin");
return
string.Format("There have been {0} unsuccessful login attempt(s) since your last successful AD login on {1}"
,numberOfFailedLoginAttempts, lastSuccessfulLogin);
}
