Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.DirectoryServices;
  7. using System.DirectoryServices.AccountManagement;
  8.  
  9. public class LdapAuthentication
  10. {
  11.     // class variables
  12.     private string _path;
  13.     private string _filterAttribute;      
  14.    
  15.     // default class constructor
  16.     public LdapAuthentication(string _domain, string _username, string _password)
  17.     {
  18.         IsAuthenticated(_domain, _username, _password);
  19.     }
  20.  
  21.     // grabs the root LDAP path for the current domain in which this program is ran
  22.     void InitializeLdapPath()
  23.     {
  24.         DirectoryEntry de = new DirectoryEntry("LDAP://RootDSE");
  25.         _path = @"LDAP://" + de.Properties["defaultNamingContext"].Value.ToString();
  26.     }
  27.  
  28.     // public method to test authentication and set our variables
  29.     public bool IsAuthenticated(string domain, string username, string pwd)
  30.     {
  31.         InitializeLdapPath();
  32.         string domainAndUsername = domain + @"\" + username;
  33.         DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
  34.         try
  35.         {
  36.             // use supplied creds to bind to ad
  37.             // this forces auth to occur
  38.             Object obj = entry.NativeObject;
  39.             DirectorySearcher searcher = new DirectorySearcher(entry);
  40.             searcher.Filter = "(SAMAccountName=" + username + ")";
  41.             searcher.PropertiesToLoad.Add("cn");
  42.             SearchResult r = searcher.FindOne();
  43.             if(r == null)
  44.             {
  45.                 return false;
  46.             }
  47.             // update our variables
  48.             _path = r.Path.ToString();
  49.             _filterAttribute = (String)r.Properties["cn"][0].ToString();
  50.         }
  51.         catch (Exception ex)
  52.         {
  53.             throw new Exception("Error authenticating user. " + ex.Message);
  54.         }
  55.  
  56.         // if everything above runs fine, return true
  57.         return true;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement