本文整理汇总了C#中System.DirectoryServices.Protocols.LdapConnection.SendRequest方法的典型用法代码示例。如果您正苦于以下问题:C# LdapConnection.SendRequest方法的具体用法?C# LdapConnection.SendRequest怎么用?C# LdapConnection.SendRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.Protocols.LdapConnection
的用法示例。
在下文中一共展示了LdapConnection.SendRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: enableCompId
/// <summary>
/// This method is to help enable the compound identity feature on the computer account in the specific domain.
/// </summary>
/// <param name="domainName">The domain name of the service principal.</param>
/// <param name="computerName">The host name of the service principal.</param>
/// <param name="adminName">Need administrator's credential to modify active directory account.</param>
/// <param name="adminPwd">Need administrator's credential to modify active directory account.</param>
public void enableCompId(string domainName, string computerName, string adminName, string adminPwd)
{
LdapConnection connection = new LdapConnection(domainName);
NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName);
connection.Credential = cred;
string dn = PacHelper.GetDomainDnFromDomainName(domainName);
string targetOu = "cn=Computers," + dn;
computerName = computerName.Replace("$", "");
string filter = "cn=" + computerName;
string[] attributesToReturn = new string[] { "msDS-SupportedEncryptionTypes" };
SearchRequest searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
object attributeValue = null;
attributeValue = PacHelper.getAttributeValue(attributes, "msDS-SupportedEncryptionTypes");
uint? supportedEncTypes = (uint?)Convert.ToInt32(attributeValue);
uint compIdFlag = 131072;
if ((supportedEncTypes.Value & compIdFlag) != compIdFlag)
{
string computerDN = filter + "," + targetOu;
supportedEncTypes = supportedEncTypes + compIdFlag;
ModifyRequest modRequest = new ModifyRequest(computerDN, DirectoryAttributeOperation.Replace, "msDS-SupportedEncryptionTypes", supportedEncTypes.ToString());
ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest);
}
}
示例2: Main
static void Main(string[] args)
{
// LdapTest <address> <domain> [<username> <password> [<domain>]]
// 0 1 2 3 4
var directory = new LdapDirectoryIdentifier(args[0]);
var credential = args.Length > 4 ? new NetworkCredential(args[2], args[3], args[4])
: args.Length > 2 ? new NetworkCredential(args[2], args[3])
: new NetworkCredential();
using (var connection = new LdapConnection(directory, credential))
{
//while (true)
{
var request = new SearchRequest(
"DC=" + args[1].Replace(".", ",DC="),
"(&(objectClass=organizationalPerson)(sAMAccountType=805306368))",
System.DirectoryServices.Protocols.SearchScope.Subtree,
new[] { "cn" }
);
try
{
var t = Stopwatch.StartNew();
PageResultRequestControl pageRequestControl = new PageResultRequestControl(1000);
// used to retrieve the cookie to send for the subsequent request
PageResultResponseControl pageResponseControl;
request.Controls.Add(pageRequestControl);
while (true)
{
var response = (SearchResponse)connection.SendRequest(request);
pageResponseControl = (PageResultResponseControl)response.Controls[0];
if (pageResponseControl.Cookie.Length == 0)
break;
pageRequestControl.Cookie = pageResponseControl.Cookie;
Console.WriteLine("{0}\t{1} entries: {2} - {3} in {4:F1}", DateTime.Now, response.Entries.Count,
AttributeOf(response.Entries[0], "cn"),
AttributeOf(response.Entries[response.Entries.Count - 1], "cn"),
t.Elapsed.TotalSeconds
);
}
t.Stop();
}
catch (Exception ex)
{
Console.WriteLine("{0}\tERRROR - {1}", DateTime.Now, ex.Message);
}
//Thread.Sleep(TimeSpan.FromSeconds(30));
}
}
}
示例3: 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;
}
}
示例4: ChangePassword
public static bool ChangePassword(LdapConnection connection, string userDN, string oldPassword, string newPassword, bool dryRun = false)
{
// Create change password request
DirectoryAttributeModification deleteMod = new DirectoryAttributeModification();
deleteMod.Name = "unicodePwd";
deleteMod.Add(Encoding.Unicode.GetBytes("\"" + oldPassword + "\""));
deleteMod.Operation = DirectoryAttributeOperation.Delete;
DirectoryAttributeModification addMod = new DirectoryAttributeModification();
addMod.Name = "unicodePwd";
addMod.Add(Encoding.Unicode.GetBytes("\"" + newPassword + "\""));
addMod.Operation = DirectoryAttributeOperation.Add;
ModifyRequest request = new ModifyRequest(userDN, deleteMod, addMod);
try
{
if (!dryRun)
{
DirectoryResponse response = connection.SendRequest(request);
return response.ResultCode == 0;
}
else
{
return true;
}
}
catch (DirectoryOperationException ex)
{
if (ex.Response.ErrorMessage.StartsWith("0000052D"))
{
throw new Exception("Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.");
}
// TODO: Convert to DirectoryOperationException and use better match to give the dsHeuristics exception
else if (ex.Message == "The object does not exist")
{
throw new Exception("User not allowed to change own password because of missing permission, set dsHeuristics to 0000000001001 on CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,CN=...");
}
else
{
throw;
}
}
}
示例5: 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;
}
示例6: 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;
}
示例7: GetRangeBlock
private static RangeResult GetRangeBlock(LdapConnection conn, string entryDn, string attrName, int start, int? end, bool extendedDns)
{
SearchRequest req = new SearchRequest();
req.DistinguishedName = entryDn;
req.Scope = SearchScope.Base;
req.Filter = "(&(objectClass=*))";
req.Attributes.Add(attrName + ";range=" + start + "-" + (end == null ? "*" : end.ToString()));
if (extendedDns)
req.Controls.Add(new ExtendedDNControl(ExtendedDNFlag.StandardString));
SearchResponse resp = (SearchResponse)conn.SendRequest(req);
if (resp.Entries.Count == 0)
return null;
SearchResultEntry e = resp.Entries[0];
foreach (string s in e.Attributes.AttributeNames)
if (s.StartsWith(attrName, StringComparison.InvariantCultureIgnoreCase))
{
RangeResult res = new RangeResult();
DirectoryAttribute attr = e.Attributes[s];
res.Values = (string[])attr.GetValues(typeof(string));
if (s.EndsWith("*"))
res.IsFinal = true;
int pos = s.IndexOf('=');
int hyp = s.IndexOf('-', pos + 1);
res.Start = int.Parse(s.Substring(pos + 1, hyp - pos - 1));
if (!res.IsFinal)
res.End = int.Parse(s.Substring(hyp + 1));
return res;
}
return null;
}
示例8: 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);
//LdapConnection lc = new LdapConnection(ldapident, null, AuthType.Basic);
var lc = new LdapConnection(ldapident, new NetworkCredential(LDAPUser, LDAPPassword), AuthType.Basic);
lc.Bind();
lc.SessionOptions.ProtocolVersion = 3;
lc.SessionOptions.SecureSocketLayer = true;
//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;
}
示例9: Delete
public void Delete(LdapConnection ldap)
{
CheckForDeletion();
if (this.IsNewEntry)
{
throw new InvalidOperationException(String.Format("Entry {0} was never committed - cannot delete",
this.DistinguishedName));
}
DeleteRequest del = new DeleteRequest(this.DistinguishedName);
ldap.SendRequest(del);
this.IsDeleted = true;
}
示例10: createUserLdap
public string createUserLdap(User user)
{
ldapId = new LdapDirectoryIdentifier(HOST, PORT);
network = new NetworkCredential(ADMIN, ADMIN_PASS);
using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
{
try
{
string[] objectClass = new string[] { "top", "inetOrgPerson", "organizationalPerson", "person" };
connection.SessionOptions.SecureSocketLayer = false;
connection.SessionOptions.ProtocolVersion = 3;
String dn = DN_CREATE.Replace("{0}", user.email);
DirectoryAttributeCollection collection = new DirectoryAttributeCollection() {
new DirectoryAttribute("objectclass", objectClass),
new DirectoryAttribute("uid",user.email),
new DirectoryAttribute("sn", user.lastName),
new DirectoryAttribute("cn", user.userName),
new DirectoryAttribute("employeeNumber", user.userId),
new DirectoryAttribute("departmentNumber", user.userGroup),
new DirectoryAttribute("userPassword", user.password)
};
AddRequest addMe = new AddRequest(dn, "inetOrgPerson");
addMe.Attributes.AddRange(collection);
connection.Bind();
connection.SendRequest(addMe);
return "OK";
}
catch (LdapException ex)
{
throw new BusinessException("Ldap error: " + ex.Message);
}
catch (Exception e)
{
throw new PlatformException("Ldap error: " + e.Message);
}
}
}
示例11: CheckLocalDirectoryUser
/// <summary>
/// Checks if the user is a local directory user.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>[true] if the user is a local directory user.</returns>
/// <remarks>Documented by Dev03, 2008-11-25</remarks>
private bool CheckLocalDirectoryUser(string username)
{
try
{
switch (connector.GetLocalDirectoryType())
{
case LocalDirectoryType.ActiveDirectory:
string domain = username.Substring(0, username.IndexOf(@"\"));
PrincipalContext context;
if (!String.IsNullOrWhiteSpace(connector.GetLdapUser()) && !String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain, connector.GetLdapUser(), connector.GetLdapPassword());
if (!String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain);
else
context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
return user != null;
case LocalDirectoryType.eDirectory:
LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(connector.GetLdapServer()));
connection.AuthType = AuthType.Basic;
connection.SessionOptions.SecureSocketLayer = connector.GetLdapUseSSL();
if (connector.GetLdapUser() != null && connector.GetLdapUser().Length > 0)
connection.Bind(new System.Net.NetworkCredential(connector.GetLdapUser(), connector.GetLdapPassword()));
else
connection.Bind();
string searchString = String.Format("(&(|(cn={0})(uid={0}))(|(objectClass=user)(objectClass=person)))",
username.Substring(username.LastIndexOf("\\") + 1));
SearchResponse response = connection.SendRequest(new SearchRequest(connector.GetLdapContext(),
searchString, SearchScope.Subtree, null)) as SearchResponse;
if (response.Entries.Count > 0)
return true;
break;
}
}
catch { return false; }
return true;
}
示例12: ValidateUser
/// <summary>
/// Authenticate a user against a AD server
/// </summary>
/// <param name="username">username to check</param>
/// <param name="password">password of the user</param>
/// <returns></returns>
public bool ValidateUser(string username, string password)
{
try
{
LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(host, port));
ldap.SessionOptions.ProtocolVersion = protocolVersion;
ldap.AuthType = AuthType.Basic;
ldap.Credential = new NetworkCredential(adminUsername, adminPassword);
ldap.SessionOptions.SecureSocketLayer = secureSocket;
ldap.Bind();
ldap.AuthType = AuthType.Basic;
SearchRequest searchRequest = new SearchRequest(
baseDn,
string.Format(CultureInfo.InvariantCulture, "{0}={1}", authUid, username),
SearchScope.Subtree
);
SearchResponse searchResponse = (SearchResponse)ldap.SendRequest(searchRequest);
if (1 == searchResponse.Entries.Count)
{
//ldap.Bind(new NetworkCredential(searchResponse.Entries[0].DistinguishedName, password));
}
else
{
throw new Exception("Login failed.");
}
}
catch (Exception e)
{
//Todo: Pass error to logging framework instead of console!
Console.WriteLine(e.Message);
return false;
}
return true;
}
示例13: queryLdap
private User queryLdap(string email)
{
string ldapFilter = "(objectClass=person)";
string ldapTarget = DN.Replace("{0}", email);
User user = new User();
network = new NetworkCredential(ADMIN, ADMIN_PASS);
ldapId = new LdapDirectoryIdentifier(HOST, PORT);
using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
{
try
{
connection.SessionOptions.SecureSocketLayer = false;
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
SearchRequest searchRequest = new SearchRequest(ldapTarget, ldapFilter, SearchScope.Subtree, "*");
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
SearchResultEntry entry = searchResponse.Entries[0];
user.email = email;
user.userId = entry.Attributes["employeeNumber"][0].ToString();
user.userName = entry.Attributes["cn"][0].ToString();
user.lastName = entry.Attributes["sn"][0].ToString();
user.userGroup = entry.Attributes["departmentNumber"][0].ToString();
connection.Dispose();
return user;
}
catch (LdapException ex)
{
throw new BusinessException(ex.Message);
}
catch (Exception e)
{
throw new PlatformException(e.Message);
}
}
}
示例14: GetBaseNamingContext
/// <summary>
/// Get the base distiguished names that will be searched for certificate resolution.
/// </summary>
/// <param name="connection">The <see cref="LdapConnection"/> connection to the LDAP server that will be searched.. </param>
/// <returns>A List of strings representing the base distiguished names of the LDAP server.</returns>
protected List<String> GetBaseNamingContext(LdapConnection connection)
{
var retVal = new List<String>();
// get the base DNs
var request = Search.NamingContextRequest();
var searchResponse = (SearchResponse)connection.SendRequest(request);
if (searchResponse == null || searchResponse.Entries == null || searchResponse.Entries.Count == 0)
{
return null;
}
try
{
foreach (SearchResultEntry entry in searchResponse.Entries)
{
if (entry.Attributes != null && entry.Attributes.Values != null && entry.Attributes.Count > 0)
{
foreach (DirectoryAttribute entryAttr in entry.Attributes.Values)
{
SetAttribute(entryAttr, retVal);
}
}
}
}
catch (Exception ldapEx)
{
this.Error.NotifyEvent(this, ldapEx);
}
return retVal;
}
示例15: IsConcurrentBindSupported
private bool IsConcurrentBindSupported(LdapConnection ldapConnection)
{
bool result = false;
Debug.Assert(ldapConnection != null);
//
// supportedExtension is a constructed attribute so we need to search and load that attribute explicitly
//
SearchRequest request = new SearchRequest();
request.Scope = System.DirectoryServices.Protocols.SearchScope.Base;
request.Attributes.Add("supportedExtension");
if (ServerSearchTimeout != -1)
request.TimeLimit = new TimeSpan(0, ServerSearchTimeout, 0);
SearchResponse response = (SearchResponse) ldapConnection.SendRequest(request);
if (response.ResultCode != ResultCode.Success)
throw new ProviderException(response.ErrorMessage);
foreach (string supportedExtension in response.Entries[0].Attributes["supportedExtension"].GetValues(typeof(string)))
{
if (StringUtil.EqualsIgnoreCase(supportedExtension, LDAP_SERVER_FAST_BIND_OID))
{
result = true;
break;
}
}
return result;
}