Validate domain user using c#
Hi,
Here am sharing code related to validate a domain user againsta active directory. This is well used for implementing authentication and authorization in asp.net or windows application.
the call should be sent a [domainname]\[username] and [password]
Here am sharing code related to validate a domain user againsta active directory. This is well used for implementing authentication and authorization in asp.net or windows application.
the call should be sent a [domainname]\[username]
public int VerifyUser(string userName, string password) { try { string domainName = string.Empty; string domainUserName = string.Empty; string[] tempString = null; string[] delimiter = new string[] { @"\" }; tempString = userName.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); if ((tempString.Length == 0) || (tempString.Length == 1)) { return 1; } domainName = tempString[0]; domainUserName = tempString[1]; LDAP.Domain_Authentication imperson = new LDAP.Domain_Authentication(domainUserName, password, domainName); if (imperson.IsValid()) { return 2; } return 3; } catch (Exception ex) { return -1; } }
And the LDAP class is as follows
namespace LDAP { using System; using System.Collections.Generic; using System.Text; using System.Security; using System.DirectoryServices.AccountManagement; public struct Credentials { public string Username; public string Password; } public class Domain_Authentication { public Credentials Credentials; public string Domain; public Domain_Authentication(string Username, string Password, string SDomain) { Credentials.Username = Username; Credentials.Password = Password; Domain = SDomain; } public bool IsValid() { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain)) { // validate the credentials return pc.ValidateCredentials(Credentials.Username, Credentials.Password); } } } }Hope this post helps you. Please do comment if any queries/suggestions.
Regards,
Pavan N
Comments
Post a Comment