https://www.codeproject.com/Tips/458039/Application-Login-through-Active-Directory-LDAP
I have tried the solution in the link above by using the validation method and modified it to return the displayname only which is pasted below. It works locally but after publishing to IIS server, it gives an error -
"Unable to cast object of type System.DirectoryServices.AccountManagement.GroupPrincipal to type 'System.DirectoryServices.AccountManagement.UserPrincipal"
I have tried to add my domain credentials in the authentication impersonate feature in IIS but then it only gives access to me, same if add different user, it will only give access to them.
NB: The website needs to get a user's current login username and Display from windows and get their details from a database. Also tried to enable windows authentication but still gives out the cast object error.
What I have tried:
public static string fnValidateUser()
{
string username = "";
string Lastname = "";
try
{
LdapConnection lcon = new LdapConnection
(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(Environment.UserName,
Environment.UserDomainName);
WindowsIdentity CurrentIdentity = WindowsIdentity.GetCurrent();
UserPrincipal userPrincipal = UserPrincipal.Current;
username = userPrincipal.DisplayName;
Lastname = userPrincipal.Surname;
// lcon.Credential = nc;
// lcon.AuthType = AuthType.Negotiate;
// // user has authenticated at this point,
// // as the credentials were used to login to the dc.
// lcon.Bind(nc);
// validation = true;
}
catch (LdapException)
{
}
return username;
}