Example #1
0
        //protected void btnWordToPdf_Click(object sender, EventArgs e)
        //{
        //    if (WordToPDF(Server.MapPath("/upload/2.docx"), Server.MapPath("/upload/2.pdf")))
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "temp", "alert('转换成功');", true);
        //        return;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "temp", "alert('转换失败');", true);
        //        return;
        //    }
        //}
        //public string PreviewWord(string physicalPath, string url)
        //{
        //    Microsoft.Office.Interop.Word._Application application = null;
        //    Microsoft.Office.Interop.Word._Document doc = null;
        //    application = new Microsoft.Office.Interop.Word.Application();
        //    object missing = Type.Missing;
        //    object trueObject = true;
        //    application.Visible = false;
        //    application.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
        //    doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,
        //      missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
        //    //Save Excel to Html
        //    object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
        //    string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
        //    String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
        //    doc.SaveAs(outputFile, format, missing, missing, missing,
        //             missing, missing, missing,
        //             missing, missing, missing, missing);
        //    doc.Close();
        //    application.Quit();
        //    return Path.GetDirectoryName(Server.UrlDecode(url)) + "\\" + htmlName;
        //}
        //public bool WordToPDF(string sourcePath, string targetPath)
        //{
        //    bool result = false;
        //    Microsoft.Office.Interop.Word._Application application = new Microsoft.Office.Interop.Word.Application();
        //    Microsoft.Office.Interop.Word._Document document = null;
        //    try
        //    {
        //        application.Visible = false;
        //        document = application.Documents.Open(sourcePath);
        //        document.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
        //        result = true;
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.Message);
        //        result = false;
        //    }
        //    finally
        //    {
        //        document.Close();
        //    }
        //    return result;
        //}

        private void CheckSchoolUser(string portal, string password)
        {
            String LDAP_Server               = "ca.zucc.edu.cn";
            int    LDAP_Port                 = 389;
            String LDAP_Search_DN            = "ou=people,dc=zucc,dc=edu,dc=cn";
            LdapDirectoryIdentifier ldapDir  = new LdapDirectoryIdentifier(LDAP_Server, LDAP_Port);
            LdapConnection          ldapConn = new LdapConnection(ldapDir);

            ldapConn.AuthType = AuthType.Basic;
            //portal是用户名,11111111是密码
            System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("uid=" + portal + "," + LDAP_Search_DN, password);
            try
            {
                ldapConn.Bind(myCredentials);
            }
            catch (LdapException e1)
            {
                Console.WriteLine("Exception in auth with LDAP Server:" + e1.Message);
                Response.Write("Auth failed!");
                return;
            }
            finally
            {
                if (ldapConn != null)
                {
                    ldapConn.Dispose();
                }
            }
            Response.Write("Auth successful!");
        }
        private bool ValidateCredentials(string username, string password, string domain)
        {
            NetworkCredential credentials
                = new NetworkCredential(username, password, domain);

            LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(domain);

            using (LdapConnection connection = new LdapConnection(id, credentials, AuthType.Kerberos))
            {
                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;

                try
                {
                    connection.Bind();
                }
                catch (LdapException lEx)
                {
                    if (lEx.ErrorCode == 49)
                    {
                        return(false);
                    }
                    throw;
                }
            }
            return(true);
        }
Example #3
0
        public bool DoAuthentication(string Domain, string User, string Password)
        {
            try
            {
                // Create the new LDAP connection
                LdapDirectoryIdentifier ldi            = new LdapDirectoryIdentifier(Domain, 389);
                LdapConnection          ldapConnection = new LdapConnection(ldi);
                Console.WriteLine("LdapConnection is created successfully.");
                ldapConnection.AuthType = AuthType.Basic;
                ldapConnection.SessionOptions.ProtocolVersion = 3;

                NetworkCredential nc = new NetworkCredential(User + "@" + Domain, Password); //password
                ldapConnection.Bind(nc);
                Console.WriteLine("LdapConnection authentication success");
                ldapConnection.Dispose();
                return(true);
            }
            catch (LdapException e)
            {
                Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
            }

            return(false);
        }
        public bool CheckCredentialServer(LdapServiceModel ldapServiceModel)
        {
            bool success = false;

            _ldapServer = ldapServiceModel.ldapServer;
            _ldapPort   = ldapServiceModel.ldapPort;
            LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(_ldapServer, Convert.ToInt16(_ldapPort), true, false);
            LdapConnection          ldapConnection          = new LdapConnection(ldapDirectoryIdentifier);

            try
            {
                ldapConnection.AuthType = AuthType.Anonymous;
                ldapConnection.AutoBind = false;
                ldapConnection.Timeout  = new TimeSpan(0, 0, 0, 1);
                ldapConnection.Bind();
                ldapConnection.Dispose();
                success = true;
            }
            catch (LdapException)
            {
                success = false;
            }

            return(success);
        }
Example #5
0
        public LdapServer()
        {
            m_conn       = null;
            m_cert       = null;
            Timeout      = (int)Registry.GetValue(LdapPluginPath, "LdapTimeout", 10);
            m_useSsl     = Convert.ToBoolean(Registry.GetValue(LdapPluginPath, "UseSsl", null).ToString());
            m_verifyCert = Convert.ToBoolean(Registry.GetValue(LdapPluginPath, "RequireCert", null));
            string certFile = (string)Registry.GetValue(LdapPluginPath, "ServerCertFile", null);

            if (m_useSsl && m_verifyCert)
            {
                if (!string.IsNullOrEmpty(certFile) && File.Exists(certFile))
                {
                    server_logger.DebugFormat("Loading server certificate: {0}", certFile);
                    m_cert = new X509Certificate2(certFile);
                }
                server_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile);
            }

            string[] ldapHost =
                (string[])Registry.GetValue(LdapPluginPath, "LdapHost", null);

            int ldapPort =
                (int)Registry.GetValue(LdapPluginPath, "LdapPort", null);

            m_serverIdentifier = new LdapDirectoryIdentifier(ldapHost, ldapPort, false, false);

            server_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, verifyCert = {3}",
                                      string.Join(", ", ldapHost), ldapPort, m_useSsl, m_verifyCert);

            this.Connect();
        }
Example #6
0
        public bool ValidateCredentials(string login, string password, out string normalizedName)
        {
            string username, domain;

            if (!tryParseDomainName(login, out username, out domain))
            {
                normalizedName = null;
                return(false);
            }

            normalizedName = $"{domain.ToUpper()}/{username.ToUpper()}";
            var credentials = new NetworkCredential(username, password, domain);

            var id = new LdapDirectoryIdentifier(domain);

            using (var connection = new LdapConnection(id, credentials, AuthType.Kerberos))
            {
                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;

                try
                {
                    connection.Bind();
                }
                catch (LdapException lEx)
                {
                    if (lEx.ErrorCode == _errorLogonFailure)
                    {
                        return(false);
                    }
                    throw;
                }
            }
            return(true);
        }
Example #7
0
        public LDAP(LdapDirectoryIdentifier inConn)
        {
            LDI              = inConn;
            theConn          = new LdapConnection(inConn);
            theConn.AuthType = AuthType.Anonymous; //anon needed to get rootDSE

            theConn.Timeout = new TimeSpan(0, 15, 0);
            getRootDSEData();

            //switch to an auth'd context
            theConn.Dispose();
            theConn = new LdapConnection(inConn);
            //add creds

            theConn.AuthType = AuthType.Negotiate;
            theConn.SessionOptions.RootDseCache = true;
            theConn.Timeout = new TimeSpan(0, 15, 0);
            theConn.SessionOptions.SendTimeout     = new TimeSpan(0, 15, 0);
            theConn.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
            theConn.SessionOptions.Signing         = true;
            theConn.SessionOptions.Sealing         = true; //the key to getting back password blobs and encryption...
            try
            {
                theConn.Bind();
            }
            catch (Exception ex)
            {
                throw new Exception("LDAP Test Bind failed", ex);
            }
        }
Example #8
0
        public static LdapConnection GetLdapConnection(string server, string userName, string password)
        {
            NetworkCredential       credentials             = new NetworkCredential(userName, password);
            LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(server);

            return(new LdapConnection(ldapDirectoryIdentifier, credentials));
        }
Example #9
0
        public LDAPHelper(
            string searchBaseDN,
            string hostName,
            int portNumber,
            AuthType authType,
            string connectionAccountName,
            SecureString connectionAccountPassword,
            int pageSize)
        {
            var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(
                hostName,
                portNumber,
                true,
                false);

            var networkCredential = new NetworkCredential(
                connectionAccountName,
                connectionAccountPassword);

            ldapConnection = new LdapConnection(
                ldapDirectoryIdentifier,
                networkCredential)
            {
                AuthType = authType
            };

            ldapConnection.SessionOptions.ProtocolVersion = 3;

            this.searchBaseDN = searchBaseDN;
            this.pageSize     = pageSize;
        }
Example #10
0
        public static string GetGPOGUID(string DomainController, string GPOName, string DistinguishedName)
        {
            // Translate GPO Name to GUID
            LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(DomainController, 389);

            LdapConnection connection = new LdapConnection(identifier);

            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();

            var new_request  = new SearchRequest(DistinguishedName, $"(displayName={GPOName})", System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var new_response = (SearchResponse)connection.SendRequest(new_request);
            var GPOGuid      = "";

            foreach (SearchResultEntry entry in new_response.Entries)
            {
                try
                {
                    GPOGuid = entry.Attributes["cn"][0].ToString();
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("[!] Could not retrieve the GPO GUID. {0}", e.Message);
                }
            }
            if (string.IsNullOrEmpty(GPOGuid))
            {
                Console.Error.WriteLine("[!] Could not retrieve the GPO GUID.");
            }

            Console.WriteLine($"[+] GUID of {GPOName} is: {GPOGuid}");
            return(GPOGuid);
        }
Example #11
0
        private LdapConnection GetLdapConnection()
        {
            if (_connectionPool.TryTake(out var connection))
            {
                return(connection);
            }

            var domainController = _domainController ?? _domainName;
            var port             = Options.Instance.LdapPort == 0
                ? (Options.Instance.SecureLDAP ? 636 : 389)
                : Options.Instance.LdapPort;
            var identifier = new LdapDirectoryIdentifier(domainController, port, false, false);

            connection = new LdapConnection(identifier);

            var ldapSessionOptions = connection.SessionOptions;

            if (!Options.Instance.DisableKerberosSigning)
            {
                ldapSessionOptions.Signing = true;
                ldapSessionOptions.Sealing = true;
            }

            ldapSessionOptions.ProtocolVersion = 3;
            ldapSessionOptions.ReferralChasing = ReferralChasingOptions.None;

            connection.Timeout = new TimeSpan(0, 5, 0);
            return(connection);
        }
Example #12
0
        public static bool Authenticated(string username, string password, string domain = "gsb")
        {
            bool isSuccess;

            try
            {
                var ldi = new LdapDirectoryIdentifier(Server, Port);

                var lc = new LdapConnection(ldi);
                var nc = new NetworkCredential(username, password, domain + ".local");

                lc.Bind(nc);

                isSuccess = true;

                lc.Dispose();
            }
            catch (LdapException)
            {
                isSuccess = false;
                // throw new LdapException(e.ErrorCode, e.Message, e.InnerException);
            }
            catch (Exception)
            {
                isSuccess = false;
                // throw new Exception();
            }

            return(isSuccess);
        }
Example #13
0
        public LDAPHelper(LDAPConnectionInfo Info)
        {
            var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(Info.HostName, Info.PortNumber, true, false);
            var qualifiedUserName       = Info.UserNameInNode + "=" + Info.UserName + "," + Info.BindDn;
            var networkCredential       = new NetworkCredential(qualifiedUserName, Info.Password);

            ldapConnection = new LdapConnection(ldapDirectoryIdentifier, networkCredential)
            {
                AuthType = Info.AuthenticationType
            };

            ldapConnection.SessionOptions.ProtocolVersion = 3;
            if (Info.VerifyServerCertificate)
            {
                ldapConnection.SessionOptions.VerifyServerCertificate += (conn, cert) => { return(true); }
            }
            ;
            if (Info.ConnectionType == LDAPConnectionInfo.ConnType.StartTLS)
            {
                ldapConnection.SessionOptions.StartTransportLayerSecurity(null);
            }

            ldapConnection.Bind();

            this.searchBaseDN = Info.BindDn;
            this.pageSize     = Info.PageSize;
        }
Example #14
0
        public LdapServer()
        {
            m_conn  = null;
            m_cert  = null;
            Timeout = Settings.Store.LdapTimeout;
            int encMethod = Settings.Store.EncryptionMethod;

            m_encryptionMethod = (Settings.EncryptionMethod)Enum.ToObject(typeof(Settings.EncryptionMethod), encMethod);
            m_verifyCert       = Settings.Store.RequireCert;
            string certFile = Settings.Store.ServerCertFile;

            if ((m_encryptionMethod == Settings.EncryptionMethod.START_TLS || m_encryptionMethod == Settings.EncryptionMethod.TLS_SSL) && m_verifyCert)
            {
                m_logger.DebugFormat("Loading server certificate: {0}", certFile);
                if (!string.IsNullOrEmpty(certFile) && File.Exists(certFile))
                {
                    m_cert = new X509Certificate2(certFile);
                }
                else
                {
                    m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile);
                }
            }

            string[] hosts = Settings.Store.LdapHost;
            int      port  = Settings.Store.LdapPort;

            m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false);

            m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, encryption = {2}, verifyCert = {3}",
                                 string.Join(", ", hosts), port, m_encryptionMethod.ToString(), m_verifyCert);

            this.Connect();
        }
Example #15
0
        public bool IsValidADUser(string username, string password)
        {
            bool userValidationFlag = true;
            var  credential         = new NetworkCredential(username, password);
            var  serverId           = new LdapDirectoryIdentifier(LDAP_SERVER);
            var  conn = new LdapConnection(serverId, credential);

            try
            {
                conn.Bind();
            }
            catch (Exception)
            {
                userValidationFlag = false;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }

            return(userValidationFlag);
        }
Example #16
0
        private static LdapConnection ConnectLDAP()
        {
            if (_ldapConnections.TryTake(out var connection))
            {
                return(connection);
            }

            var identifier = new LdapDirectoryIdentifier(dc, port, false, false);

            connection = (username != null) ?
                         new LdapConnection(identifier, new NetworkCredential(username, _password)) :
                         new LdapConnection(identifier);

            connection.SessionOptions.Signing         = true;
            connection.SessionOptions.Sealing         = true;
            connection.SessionOptions.ProtocolVersion = 3;
            connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
            connection.SessionOptions.SendTimeout     = new TimeSpan(0, 0, 10, 0);
            connection.Timeout = new TimeSpan(0, 0, 10, 0);

            connection.SessionOptions.SecureSocketLayer = useLdaps ? true : false;

            _ldapConnections.Add(connection);
            return(connection);
        }
Example #17
0
        /// <summary>
        /// Creates a connection to an LDAP server based on the DNS SRV resolution of the lookup name.
        /// </summary>
        /// <param name="srvRecord">Resolver <see cref="SRVRecord"/></param>
        /// <returns>An <see cref="LdapConnection"/> to the server that will be searched for certificates.</returns>
        protected LdapConnection GetLdapConnection(SRVRecord srvRecord)
        {
            LdapConnection retVal;

            var ldapIdentifier = new LdapDirectoryIdentifier(srvRecord.Target, srvRecord.Port);

            try
            {
                retVal          = new LdapConnection(ldapIdentifier);
                retVal.AuthType = AuthType.Anonymous; // use anonymous bind
                retVal.SessionOptions.ProtocolVersion = LdapProtoVersion;

                if (Timeout.Ticks > 0)
                {
                    retVal.Timeout = Timeout;
                }
                retVal.Bind();
            }
            catch (Exception ex)
            {
                // didn't connenct.... go onto the next record
                this.Error.NotifyEvent(this, new LdapCertResolverException(LDAPError.BindFailure, srvRecord.ToString(), ex));
                retVal = null;
            }
            return(retVal);
        }
        private static bool ValidateLdapCredentials(string userName, string password, string domain)
        {
            LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(domain);
            var credentials = new NetworkCredential(userName, password, domain);

            using (var connection = new LdapConnection(directoryIdentifier, credentials, AuthType.Kerberos))
            {
                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;

                try
                {
                    connection.Bind();
                }
                catch (LdapException ex)
                {
                    if (ex.ErrorCode == ErrorLoginFailure)
                    {
                        return(false);
                    }
                    throw;
                }
            }
            return(true);
        }
Example #19
0
        private LdapConnection ConnectLDAP()
        {
            if (EnableLdapClaimResolution)
            {
                Validate();
                var di = new LdapDirectoryIdentifier(Servers, true, false);
                if (string.IsNullOrEmpty(MachineAccountName))
                {
                    // Use default credentials
                    _ldapConnection = new LdapConnection(di, null, AuthType.Kerberos);
                }
                else
                {
                    // Use specific specific machine account
                    var machineAccount = MachineAccountName + "@" + Domain;
                    var credentials    = new NetworkCredential(machineAccount, MachineAccountPassword);
                    _ldapConnection = new LdapConnection(di, credentials);
                }
                _ldapConnection.SessionOptions.ProtocolVersion = 3; //Setting LDAP Protocol to latest version
                _ldapConnection.Timeout = TimeSpan.FromMinutes(1);

                _ldapConnection.Bind(); // This line actually makes the connection.
            }
            return(_ldapConnection);
        }
Example #20
0
        public LdapServer()
        {
            m_conn       = null;
            m_cert       = null;
            Timeout      = Settings.Store.LdapTimeout;
            m_useSsl     = Settings.Store.UseSsl;
            m_useTls     = Settings.Store.UseTls;
            m_verifyCert = Settings.Store.RequireCert;
            string certFile = Settings.Store.ServerCertFile;

            if ((m_useSsl || m_useTls) && m_verifyCert)
            {
                if (!string.IsNullOrEmpty(certFile) && File.Exists(certFile))
                {
                    m_logger.DebugFormat("Loading server certificate: {0}", certFile);
                    m_cert = new X509Certificate2(certFile);
                }
                else
                {
                    m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile);
                }
            }

            string[] hosts = Settings.Store.LdapHost;
            int      port  = Settings.Store.LdapPort;

            m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false);

            m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, useTLS = {3}, verifyCert = {4}",
                                 string.Join(", ", hosts), port, m_useSsl, m_useTls, m_verifyCert);

            pGinaSettings = pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" });

            this.Connect();
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string username = req.Query["username"];
            string password = req.Query["password"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            username = username ?? data?.username;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                string responseMessage = "Parameters Missing";
                return(new OkObjectResult(responseMessage));
            }



            bool authenticated = false;

            try
            {
                LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(Environment.GetEnvironmentVariable("LDAP_SERVER"), 389);
                System.DirectoryServices.Protocols.LdapConnection ldapConnection =
                    new System.DirectoryServices.Protocols.LdapConnection(ldi);
                Console.WriteLine("LdapConnection is created successfully.");
                ldapConnection.AuthType = AuthType.Basic;
                ldapConnection.SessionOptions.ProtocolVersion = 3;
                NetworkCredential nc = new NetworkCredential("uid=" + username + ",ou=people,dc=eastus,dc=cloudapp,dc=azure,dc=com",
                                                             password);
                ldapConnection.Bind(nc);
                Console.WriteLine("LdapConnection authentication success");
                ldapConnection.Dispose();
                authenticated = true;
            }
            catch (DirectoryServicesCOMException cex)
            {
                log.LogInformation(cex.ToString());
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.ToString());
            }



            if (authenticated != true)
            {
                string Message = "USER NOT AUTHENTICATED";
                return(new OkObjectResult(Message));
            }
            else
            {
                string Message = "User is Auth in this organization unit";
                return(new OkObjectResult(Message));
            }
        }
Example #22
0
        private LdapConnection GetLdapConnection()
        {
            if (_connectionPool.TryTake(out var connection))
            {
                return(connection);
            }

            var domainController = _domainController ?? _domainName;
            var port             = _ldapPort == 0
                ? (_secureLdap ? 636 : 389)
                : _ldapPort;
            var identifier = new LdapDirectoryIdentifier(domainController, port, false, false);

            connection = _ldapUsername != null ? new LdapConnection(identifier, new NetworkCredential(_ldapUsername, _ldapPassword)) : new LdapConnection(identifier);

            var ldapSessionOptions = connection.SessionOptions;

            /*
             * if (!Options.Instance.DisableKerberosSigning)
             * {
             *  ldapSessionOptions.Signing = true;
             *  ldapSessionOptions.Sealing = true;
             * }
             */
            ldapSessionOptions.ProtocolVersion = 3;
            ldapSessionOptions.ReferralChasing = ReferralChasingOptions.None;
            ldapSessionOptions.SendTimeout     = new TimeSpan(0, 0, 10, 0);

            connection.Timeout = new TimeSpan(0, 0, 10, 0);
            return(connection);
        }
Example #23
0
        /// <summary>
        /// Método que se encarga de obtener el nombre de una persona a partir de su nombre de usuario (login)
        /// </summary>
        /// <param name="nombreUsuario">Nombre de usuario (login)</param>
        /// <returns>Nombre de la persona</returns>

        public String obtenerNombrePersona(string nombreUsuario)
        {
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            try
            {
                String nombrePersona;
                // Crear conexion con LDAP
                openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
                openLdap.AuthType   = AuthType.Basic;
                openLdap.SessionOptions.ProtocolVersion = 3;                  // Hay que usar LDAPv3
                openLdap.Bind();                                              //Conectar
                string[] attributesToReturn = new string[] { "displayName" }; // Atributos a retornar
                // Buscar al usuario por su login
                SearchRequest searchRequest = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + nombreUsuario + "*)",
                                                                System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn);
                SearchResponse     searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);             // Respuesta del servidor
                DirectoryAttribute atributo       = searchResponse.Entries[0].Attributes["displayName"];
                object[]           objeto         = atributo.GetValues(Type.GetType("System.Byte[]"));
                nombrePersona = Encoding.ASCII.GetString((byte[])objeto[0]);
                openLdap.Dispose();                 // Liberar recursos
                return(nombrePersona);
            }
            catch (Exception e)
            {
                openLdap.Dispose();
                _conexionBD = new ManejoBD();
                _conexionBD.insertarBitacoraError(e.ToString(), "");
                return(null);
            }
        }
Example #24
0
        public static SearchResponse GetSearchResponse(string searchFilter, string searchBase)
        {
            //Establishing a Connection to the LDAP Server
            var ldapident = new LdapDirectoryIdentifier(STR_LDAPURL, STR_LDAPPort);
            //LdapConnection lc = new LdapConnection(ldapident, null, AuthType.Basic);
            var lc = new LdapConnection(ldapident, new NetworkCredential(LDAPUser, LDAPPassword), AuthType.Basic);

            lc.SessionOptions.ProtocolVersion   = 3;
            lc.SessionOptions.SecureSocketLayer = true;
            lc.Bind();

            //Configure the Search Request to Query the UCD OpenLDAP Server's People Search Base for a Specific User ID or Mail ID and Return the Requested Attributes
            var attributesToReturn = new string[]
            {
                STR_UID, STR_EmployeeNumber, STR_Mail, STR_Telephone, STR_DisplayName, STR_CN,
                STR_SN, STR_GivenName, STR_PIDM
            };

            var sRequest = new SearchRequest(searchBase, searchFilter, SearchScope.Subtree, attributesToReturn);

            //Send the Request and Load the Response
            var sResponse = (SearchResponse)lc.SendRequest(sRequest);

            return(sResponse);
        }
Example #25
0
        private LdapDirectoryIdentifier CreateIdentifier()
        {
            string connectionString    = this.ServerIP + ":" + this.PortNumber;
            LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(connectionString);

            return(id);
        }
Example #26
0
 public static bool Bind(string username, string password)
 {
     if (password.Length > 0)
     {
         try
         {
             LdapDirectoryIdentifier LDAPdi         = new LdapDirectoryIdentifier("ldap.pmhu.local", 389);
             LdapConnection          ldapConnection = new LdapConnection(LDAPdi);
             ldapConnection.AuthType = AuthType.Basic;
             ldapConnection.SessionOptions.ProtocolVersion = 3;
             NetworkCredential networkCredential = new NetworkCredential(username + "@pmhu.local", password);
             ldapConnection.Bind(networkCredential);
             ldapConnection.Dispose();
             return(true);
         }
         catch (LdapException e)
         {
             Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
         }
         catch (Exception e)
         {
             Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
         }
     }
     return(false);
 }
Example #27
0
        private static LdapConnection ConnectLDAP()
        {
            if (_ldapConnections.TryTake(out var connection))
            {
                return(connection);
            }

            var identifier = new LdapDirectoryIdentifier(dc, port, false, false);

            connection = (username != null) ?
                         new LdapConnection(identifier, new NetworkCredential(username, _password)) :
                         new LdapConnection(identifier);
            //new LdapConnection(identifier, new NetworkCredential(string.Empty, string.Empty))
            //{
            //    AuthType = AuthType.Anonymous
            //};
            connection.SessionOptions.SecureSocketLayer = useLdaps ? true : false;
            if (!disableSigning)
            {
                connection.SessionOptions.Signing = true;
                connection.SessionOptions.Sealing = true;
            }

            connection.SessionOptions.ProtocolVersion = 3;
            connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
            connection.SessionOptions.SendTimeout     = new TimeSpan(0, 0, 10, 0);
            connection.Timeout  = new TimeSpan(0, 0, 10, 0);
            connection.AuthType = AuthType.Negotiate;
            connection.SessionOptions.VerifyServerCertificate += delegate { return(true); };

            _ldapConnections.Add(connection);
            return(connection);
        }
Example #28
0
        public static string[] GetUserData(String Login)
        {
            string[] servers = { @"dc1.labs.wmi.amu.edu.pl", @"dc2.labs.wmi.amu.edu.pl" };
            string   suffix  = @"labs.wmi.amu.edu.pl";
            int      port    = 636;
            string   root    = @"DC=labs,DC=wmi,DC=amu,DC=edu,DC=pl";

            string[] userData = new string[3];
            try
            {
                LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(servers[0], port, true, false);
                LdapConnection          lc  = new LdapConnection(ldi);
                lc.AuthType = AuthType.Anonymous;
                lc.Bind();

                string   filter             = String.Format("(&(objectCategory=person)(sAMAccountName={0}))", Login);
                string[] attributesToReturn = { "sAMAccountName", "givenname", "sn", "mail" };

                SearchRequest  sreq = new SearchRequest(root, filter, SearchScope.Subtree, attributesToReturn);
                SearchResponse sres = lc.SendRequest(sreq) as SearchResponse;

                string fname = (string)sres.Entries[0].Attributes["givenname"].GetValues(typeof(String))[0];
                string sname = (string)sres.Entries[0].Attributes["sn"].GetValues(typeof(String))[0];
                string email = (string)sres.Entries[0].Attributes["mail"].GetValues(typeof(String))[0];

                return(new string[] { fname, sname, email });
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #29
0
        public static bool ValidateLDAP(LoginViewModel model)
        {
            string[] servers = { @"dc1.labs.wmi.amu.edu.pl", @"dc2.labs.wmi.amu.edu.pl" };
            string   suffix  = @"labs.wmi.amu.edu.pl";
            int      port    = 636;
            string   root    = @"DC=labs,DC=wmi,DC=amu,DC=edu,DC=pl";


            try
            {
                LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(servers[0], port, true, false);
                LdapConnection          lc  = new LdapConnection(ldi);

                lc.AuthType = AuthType.Kerberos;

                String ldapUser = String.Format("{0}@{1}", model.UserName, suffix);
                lc.Credential = new NetworkCredential(ldapUser, model.Password);

                lc.Bind();
                return(true);
            }
            catch (LdapException e)
            {
                if (e.Message.Contains("Podane poświadczenie jest nieprawidłowe.") || e.Message.Contains("The supplied credential is invalid."))
                {
                    return(false);
                }
                throw e;
            }
            return(false);
        }
Example #30
0
        /// <summary>
        /// Initialize and return the connection object without make the Bind operation
        /// </summary>
        /// <param name="hostname"></param>
        /// <param name="port"></param>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>Initialized object to LDAP server to be binded by external code</returns>
        public static LdapConnection CreateClient(string hostname, int port, string domain, string username, string password)
        {
            var credentials = new NetworkCredential(username, password, domain);
            var serverId    = new LdapDirectoryIdentifier(hostname, port);

            return(new LdapConnection(serverId, credentials));
        }
	public LdapConnection(LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, AuthType authType) {}
	public LdapConnection(LdapDirectoryIdentifier identifier) {}