本文整理汇总了C#中System.DirectoryServices.Protocols.LdapConnection.Bind方法的典型用法代码示例。如果您正苦于以下问题:C# LdapConnection.Bind方法的具体用法?C# LdapConnection.Bind怎么用?C# LdapConnection.Bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.Protocols.LdapConnection
的用法示例。
在下文中一共展示了LdapConnection.Bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Connect
public LdapState Connect(NetworkCredential credential)
{
try
{
_ldapConnection = LdapConnectionFactory.GetLdapConnection(credential, _configRepository);
if (_adminModeChecker.IsAdminMode()) _ldapConnection.Bind(credential);
if (_adminModeChecker.IsAnonymousMode()) _ldapConnection.Bind(credential);
}
catch (Exception e)
{
string errorConnectionMessage = String.Format("{0}\n User: {1}\n Pwd: {2}{3}{4}{5}",
e.Message,
credential.UserName,
credential.Password,
(_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""),
(_configRepository.GetTransportSocketLayerFlag()? "\n With TLS " : ""),
(_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : ""));
_logger.Write(_logger.BuildLogMessage(errorConnectionMessage, LdapState.LdapConnectionError));
return LdapState.LdapConnectionError;
}
var successConnectionMessage = String.Format("Connection success\n User: {0}\n Pwd: {1}{2}{3}{4}",
credential.UserName,
credential.Password,
(_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""),
(_configRepository.GetTransportSocketLayerFlag() ? "\n With TLS " : ""),
(_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : ""));
if (_adminModeChecker.IsNoAdminMode())
_ldapConnection.Dispose();
_logger.Write(_logger.BuildLogMessage(successConnectionMessage, LdapState.LdapConnectionSuccess));
return LdapState.LdapConnectionSuccess;
}
示例2: GetSearchResponse
public static SearchResponse GetSearchResponse(string searchFilter, string searchBase, int sizeLimit = 500)
{
//Establishing a Connection to the LDAP Server
//var ldapident = new LdapDirectoryIdentifier(STR_LDAPURL, STR_LDAPPort);
var ldapident = new LdapDirectoryIdentifier(STR_LDAPOLD, STR_LDAPPort);
//LdapConnection lc = new LdapConnection(ldapident, null, AuthType.Basic);
using (var lc = new LdapConnection(ldapident, new NetworkCredential(LDAPUser, LDAPPassword), AuthType.Basic))
{
lc.SessionOptions.ProtocolVersion = 3;
lc.SessionOptions.SecureSocketLayer = true;
lc.SessionOptions.VerifyServerCertificate = (connection, certificate) => 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) { SizeLimit = sizeLimit };
//Send the Request and Load the Response
var sResponse = (SearchResponse)lc.SendRequest(sRequest);
return sResponse;
}
}
示例3: authenticateBoundary
public User authenticateBoundary(string email, string password)
{
ldapId = new LdapDirectoryIdentifier(HOST, PORT);
network = new NetworkCredential(DN.Replace("{0}", email), password);
using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
{
try
{
connection.SessionOptions.SecureSocketLayer = false;
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
connection.Dispose();
return queryLdap(email);
}
catch (LdapException ex)
{
throw new BusinessException(ex.Message);
}
catch (Exception e)
{
throw new PlatformException(e.Message);
}
}
}
示例4: StandardConnect
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected void StandardConnect(NetworkCredential credential)
{
if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.UserName})) throw new InvalidCredentialException("Username cannot be null or empty");
if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.Password})) throw new InvalidCredentialException("Password cannot be null or empty");
_ldapConnection = LdapConnectionFactory.GetLdapConnection(_configRepository);
_ldapConnection.Bind(credential);
}
示例5: Client
public Client(string username, string domain, string password, string url)
{
var credentials = new NetworkCredential(username, password, domain);
var serverId = new LdapDirectoryIdentifier(url);
connection = new LdapConnection(serverId, credentials);
connection.Bind();
}
示例6: ConnectLDAP
public bool ConnectLDAP()
{
m_LdapConnection = new LdapConnection(m_LdapServer);
m_LdapConnection.SessionOptions.ProtocolVersion = 3;
m_LdapConnection.AuthType = AuthType.Basic;
m_LdapConnection.Credential = m_Credential;
m_LdapConnection.Bind();
return true;
}
示例7: Start
public void Start()
{
Guard.IsNull(_connection, "You may only call Start one time.");
_connection = new LdapConnection(
new LdapDirectoryIdentifier(_adServer),
null, AuthType.Negotiate);
_connection.Bind();
_timer = new Timer(timerCallback, null,
TimeSpan.FromSeconds(0),
pollingInterval);
}
示例8: IsAuthenticated
public bool IsAuthenticated(string username, string pwd)
{
ILog log = LogManager.GetLogger(GetType());
try
{
log.InfoFormat("连接Ldap服务器,server是{0}", Server);
var connection = new LdapConnection(Server)
{
AuthType = AuthType.Basic
};
connection.SessionOptions.ProtocolVersion = 3;
if (!AnonymousLogin)
{
log.InfoFormat("使用Credential账户是{0},密码是{1}", CredentialUserName, CredentialPassword);
connection.Credential = new NetworkCredential(CredentialUserName, CredentialPassword ?? "");
}
if (IsSsl)
{
log.Info("使用SSL连接");
connection.SessionOptions.SecureSocketLayer = true;
}
log.DebugFormat("创建SearchRequest,distinguishedName是{0},filter是{1}", SearchUserPath, "uid=" + username);
var searchRequestion = new SearchRequest(SearchUserPath, "uid=" + username, SearchScope.Subtree);
var searchResult = (SearchResponse)connection.SendRequest(searchRequestion, new TimeSpan(0, 0, 0, 30));
if (searchResult.Entries.Count == 0)
{
log.InfoFormat("无法通过找到用户.distinguishedName是{0},filter是{1}", SearchUserPath, "uid=" + username);
return false;
}
SearchResultEntry entry = searchResult.Entries[0];
string dn = entry.DistinguishedName;
log.InfoFormat("DN是{0}", dn);
connection.Credential = new NetworkCredential(dn, pwd);
connection.Bind();
return true;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
return false;
}
}
示例9: Authenticate
public bool Authenticate(string password)
{
try
{
var credential = new NetworkCredential(UserName, password, Domain);
var ldapServer = Domain;
var ldapConnection = new LdapConnection(ldapServer);
ldapConnection.Bind(credential);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
return false;
}
示例10: ValidateUserInternal
public bool ValidateUserInternal(string username, string password)
{
LdapConnection connection = new LdapConnection(Domain);
try
{
connection.Bind(new NetworkCredential(username, password));
}
catch
{
return false;
}
finally
{
connection.Dispose();
}
return true;
}
示例11: AuthenticateUser
public ValidationResult AuthenticateUser(UserDetails user)
{
ValidationResult validationResult = null;
try
{
LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier(_adServerAddress, _ldapPortNumber));
NetworkCredential nc = new NetworkCredential(user.UserName, user.Password, Environment.UserDomainName);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
lcon.Bind(nc);
validationResult = new ValidationResult(true, false, null);
}
catch (LdapException e)
{
//tbd - investigate other possible ldap exceptions
//if (e.Message == "The supplied credential is invalid.")
if (e.ErrorCode.Equals(LDAPError_InvalidCredentials))
{
validationResult = new ValidationResult(false, true, e.Message);
}
else
{
//implement logging and exception email handling here.
validationResult = new ValidationResult(false, true, "A system error occured, please contact system administrator and/or check system logs.");
}
}
catch (Exception e)
{
validationResult = new ValidationResult(false, true, "A system error occured, please contact system administrator and/or check system logs.");
//add new fields for error logging
var errorLoggingWSClient = new ErrorLoggingServiceClient();
errorLoggingWSClient.LogApplicationError(new ApplicationErrorRequest()
{
ApplicationName = "KingstonWharvesWS.ADAuthentication"
});
}
return validationResult;
}
示例12: autenticarUsuario
/// <summary>
/// Autentica a un usuario contra openLDAP y verifica su membresia en alguno de los grupos
/// </summary>
/// <param name="nombreUsuario">Nombre de usuario</param>
/// <param name="password">Contraseña del usuario</param>
/// <returns>El grupo al que pertenece el usuario o null en caso que no esté registrado.</returns>
public GrupoLDAP autenticarUsuario(string nombreUsuario, string password)
{
// Valida usuario y contraseña correctos
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential("uid=" + nombreUsuario + ",ou=people,dc=ic-itcr,dc=ac,dc=cr", password);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3;
try
{
openLdap.Bind();
}
catch (Exception e)
{
openLdap.Dispose();
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
return null;
}
// Buscar grupo al que pertenezca el usuario
foreach (GrupoLDAP grupo in _listadaGrupos.obtenerGruposLDAP())
{
SearchRequest searchRequest = new SearchRequest("cn=" + grupo.NombreGrupo + ",ou=group,dc=ic-itcr,dc=ac,dc=cr", "(memberUid=" + nombreUsuario + ")", System.DirectoryServices.Protocols.SearchScope.Subtree);
try
{
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);
if (searchResponse.Entries.Count != 0)
{
openLdap.Dispose();
return grupo;
}
}
catch (Exception e)// En caso que algún grupo registrado en ListadoGruposLDAP.getGroupList() no exista.
{
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "Algún grupo registrado en ListadoGruposLDAP.getGroupList() no existe.");
continue;
}
}
openLdap.Dispose();
return null;
}
示例13: ValidateUsernameAndPassword
public LdapUserModel ValidateUsernameAndPassword(string username, string password)
{
var ldapServer = Configuration.Server;
var baseDn = Configuration.BaseDn;
try
{
LdapConnection connection = new LdapConnection(ldapServer);
connection.SessionOptions.SecureSocketLayer = true;
connection.SessionOptions.VerifyServerCertificate = (ldapConnection, certificate) => true;
connection.AuthType = AuthType.Negotiate;
NetworkCredential credential = new NetworkCredential(username, password);
connection.Credential = credential;
connection.Bind();
string filter = string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", LdapEncode(username));
var attributes = new[] { "sAMAccountName", "displayName", "mail" };
SearchRequest searchRequest = new SearchRequest(baseDn, filter, SearchScope.Subtree, attributes);
var searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse?.ResultCode == ResultCode.Success)
{
var entry = searchResponse.Entries[0];
var model = new LdapUserModel
{
Identity = GetStringValue(entry, "sAMAccountName"),
Email = GetStringValue(entry, "mail"),
Username = GetStringValue(entry, "sAMAccountName"),
};
return model;
}
}
catch (Exception)
{
return null;
}
return null;
}
示例14: CheckUserCredential
public bool CheckUserCredential(String UserName, String Password)
{
try
{
LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(_ldapServers, _ldapPort, true, false);
LdapConnection lc = new LdapConnection(ldi);
lc.AuthType = AuthType.Kerberos;
String ldapUser = String.Format("{0}@{1}", UserName, _userSuffix);
lc.Credential = new NetworkCredential(ldapUser, Password);
lc.Bind();
return true;
}
catch (Exception e)
{
throw;
}
}
示例15: InitializeTest
public void InitializeTest()
{
ISchemaInfo target = new AdsSchemaInfo();
using (LdapConnection conn = new LdapConnection("localhost:20389"))
{
conn.Bind(System.Net.CredentialCache.DefaultNetworkCredentials);
target.Initialize(conn);
}
int ocs = 0;
foreach (ObjectClassSchema o in target.ObjectClasses)
{
System.Console.WriteLine("oc: {0}", o);
foreach (AttributeSchema a in o.MustHave)
System.Console.WriteLine(" must: {0} as {1}", a, a.LangType);
foreach (AttributeSchema a in o.MayHave)
System.Console.WriteLine(" may : {0} as {1}", a, a.LangType);
ocs++;
}
Assert.IsTrue(ocs >= 10, "At least 10 object classes found");
ObjectClassSchema user = target.GetObjectClass("USER");
Assert.IsTrue(user != null, "Found 'USER' (mixed case) objectclass");
user = target.GetObjectClass("NO-SUCH-THING");
Assert.IsNull(user);
AttributeSchema attr = target.GetAttribute("cn");
Assert.IsNotNull(attr);
attr = target.GetAttribute("NO-ATTRIBUTE");
Assert.IsNull(attr);
}