- 1 year ago
Access denied reset Password LDAP .net 6
To reset a password in LDAP using .NET 6, you can use the System.DirectoryServices.Protocols
namespace, which provides the LdapConnection
class to establish a connection to the LDAP server and perform operations such as resetting a user's password.
Here is an example code snippet that demonstrates how to reset a user's password in LDAP using .NET 6:
csharpusing System;
using System.DirectoryServices.Protocols;
class Program
{
static void Main(string[] args)
{
string username = "username";
string oldPassword = "oldpassword";
string newPassword = "newpassword";
string ldapServer = "ldap://yourldapserver.com";
string searchBase = "ou=users,dc=example,dc=com";
try
{
// Create a new LdapConnection object and bind to the LDAP server
using (LdapConnection connection = new LdapConnection(ldapServer))
{
connection.AuthType = AuthType.Basic;
connection.Credential = new System.Net.NetworkCredential(username, oldPassword);
connection.Bind();
// Search for the user to reset the password for
string filter = $"(&(objectClass=user)(sAMAccountName={username}))";
SearchRequest searchRequest = new SearchRequest(searchBase, filter, SearchScope.Subtree);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse.Entries.Count == 0)
{
Console.WriteLine($"User {username} not found.");
}
else if (searchResponse.Entries.Count > 1)
{
Console.WriteLine($"Multiple users found with username {username}.");
}
else
{
// Get the distinguished name of the user
string dn = searchResponse.Entries[0].DistinguishedName;
// Modify the user's password
DirectoryAttributeModification modification = new DirectoryAttributeModification();
modification.Name = "unicodePwd";
modification.Add(Encoding.Unicode.GetBytes($"\"{newPassword}\""));
ModifyRequest modifyRequest = new ModifyRequest(dn, modification);
ModifyResponse modifyResponse = (ModifyResponse)connection.SendRequest(modifyRequest);
if (modifyResponse.ResultCode == ResultCode.Success)
{
Console.WriteLine($"Password reset for user {username}.");
}
else
{
Console.WriteLine($"Password reset for user {username} failed. Error code: {modifyResponse.ResultCode}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
This code uses the LdapConnection
class to establish a connection to the LDAP server and authenticate the user using their old password. Then, it searches for the user in the LDAP directory using their username, retrieves their distinguished name, and resets their password by modifying the unicodePwd
attribute with the new password. Finally, it prints a success or error message based on the result of the password reset operation.