Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.DirectoryServices;
- using System.DirectoryServices.AccountManagement;
- public class LdapAuthentication
- {
- // class variables
- private string _path;
- private string _filterAttribute;
- // default class constructor
- public LdapAuthentication(string _domain, string _username, string _password)
- {
- IsAuthenticated(_domain, _username, _password);
- }
- // grabs the root LDAP path for the current domain in which this program is ran
- void InitializeLdapPath()
- {
- DirectoryEntry de = new DirectoryEntry("LDAP://RootDSE");
- _path = @"LDAP://" + de.Properties["defaultNamingContext"].Value.ToString();
- }
- // public method to test authentication and set our variables
- public bool IsAuthenticated(string domain, string username, string pwd)
- {
- InitializeLdapPath();
- string domainAndUsername = domain + @"\" + username;
- DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
- try
- {
- // use supplied creds to bind to ad
- // this forces auth to occur
- Object obj = entry.NativeObject;
- DirectorySearcher searcher = new DirectorySearcher(entry);
- searcher.Filter = "(SAMAccountName=" + username + ")";
- searcher.PropertiesToLoad.Add("cn");
- SearchResult r = searcher.FindOne();
- if(r == null)
- {
- return false;
- }
- // update our variables
- _path = r.Path.ToString();
- _filterAttribute = (String)r.Properties["cn"][0].ToString();
- }
- catch (Exception ex)
- {
- throw new Exception("Error authenticating user. " + ex.Message);
- }
- // if everything above runs fine, return true
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement