根据您的 Active Directory 策略,可能需要交互式登录尝试来锁定帐户。您可以使用LogonUser
advapi32.dll 的方法模拟那些。在我的测试中,我发现运行此循环 100 次并不能保证在域控制器上尝试 100 次错误密码,因此您应该检查用户是否被锁定并在必要时进行更多尝试。
这样做的底线是您应该禁用帐户而不是尝试锁定它。锁定帐户和禁用帐户之间没有功能差异。下面的代码是一个黑客。
using System;
using System.Runtime.InteropServices;
namespace Test
{
class Program
{
static void Main(string[] args)
{
IntPtr token = IntPtr.Zero;
string userPrincipalName = "userID@domain.com";
string authority = null; // Can be null when using UPN (user principal name)
string badPassword = "bad";
int maxTries = 100;
bool res = false;
for (var i = 0; i < maxTries; i++)
{
res = LogonUser(userPrincipalName, authority, badPassword, LogonSessionType.Interactive, LogonProvider.Default, out token);
CloseHandle(token);
}
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string principal,
string authority,
string password,
LogonSessionType logonType,
LogonProvider logonProvider,
out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonSessionType : uint
{
Interactive = 2,
Network,
Batch,
Service,
NetworkCleartext = 8,
NewCredentials
}
enum LogonProvider : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
}
}