mardi 26 mars 2019

how to connect with AD

 public bool IsAuthenticated(string domain, string username, string pwd, string request)
        {
            bool isAuthenticated = false;
            string domainAndUsername;

            if (!string.IsNullOrWhiteSpace(domain))
            {
                domainAndUsername = domain + @"\" + username;
            }
            else
            {
                domainAndUsername = username;
            }

            _Log.Info("Parameters :");
            _Log.InfoFormat("Username. : {0}", domainAndUsername);
            _Log.InfoFormat("Path......: {0}", _path);

            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

            if (entry == null)
                _Log.Error("No Directory Entry !!!");

            _Log.Info("DirectoryEntry informations :");

            _Log.InfoFormat("- AuthenticationType. : {0}", entry.AuthenticationType);
            _Log.InfoFormat("- Path............... : {0}", entry.Path);

            try
            {
                //Bind to the native AdsObject to force authentication.
                object obj = entry.NativeObject;

                _Log.Info("User search ...");

                DirectorySearcher search = new DirectorySearcher(entry);

                search.Filter = String.Format(request, username);

                _Log.InfoFormat("Filtering : {0}", search.Filter);

                search.PropertiesToLoad.Add("cn");

                _Log.InfoFormat("Properties loaded : {0}", string.Join(", ", search.PropertiesToLoad));

                SearchResult result = search.FindOne();

                if (result != null)
                {
                    _Log.InfoFormat("Result found : {0}", result.ToString());
                    isAuthenticated = true;
                }
                else
                {
                    _Log.Warn("No results !");
                }
            }
            catch (Exception ex)
            {
                _Log.Error("LDAP authentication error", ex);
                throw new Exception("Error authenticating user : " + username + ", pwd : " + new String('*', pwd.Length) + ", domain : " + domain + ", request : " + request);
            }

            return isAuthenticated;
        }