.net core在非windows平台下修改AD用户密码完整代码
时间: 2024-03-12 11:46:52 浏览: 32
以下使用 .NET Core 在非 Windows 平台下修改 AD 用户密码的完整代码示例:
```csharp
using System;
using System.DirectoryServices.AccountManagement;
namespace ADPasswordChangeExample
{
class Program
{
static void Main(string[] args)
{
// AD 连接信息
string adServer = "ldap://your.ad.server.com";
string adUser = "CN=Administrator,CN=Users,DC=yourdomain,DC=com";
string adPassword = "yourPassword";
// 用户信息
string username = "testuser";
string oldPassword = "oldPassword";
string newPassword = "newPassword";
// 建立 AD 连接
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, adServer, adUser, adPassword))
{
// 查找用户
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
if (user != null)
{
// 认证用户
bool isAuthenticated = context.ValidateCredentials(username, oldPassword);
if (isAuthenticated)
{
// 修改密码
user.SetPassword(newPassword);
user.Save();
Console.WriteLine("Password changed successfully.");
}
else
{
Console.WriteLine("Authentication failed. Please check the old password.");
}
}
else
{
Console.WriteLine("User not found.");
}
}
Console.ReadLine();
}
}
}
```
请注意,要在非 Windows 平台上运行此代码,您需要通过 NuGet 包管理器安装 `System.DirectoryServices.AccountManagement` 包。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)