AD域账号验证

public partial class _Default : Page
{
[DllImport("advapi32.dll")]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
protected void Page_Load(object sender, EventArgs e)
{
lblLocaAdAccount.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}

protected void btnSave_Click(object sender, EventArgs e)
{
string strDomain = txtDomain.Text.Trim();
string strUserName = txtUserName.Text.Trim();
string strPassWord = txtPassWord.Text.Trim();

lblMsg.Text = "验证中…";
bool isAccount = ValidateUserAccount(strDomain, strUserName, strPassWord);
if (isAccount)
{
lblMsg.Text = "合法用户";
}
else {
lblMsg.Text = "非法用户";
}


if (isAccount)
{
//完全采用域用户来管理
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
strUserName, // user name
DateTime.Now, // issue time
DateTime.Now.AddHours(1), // expires every hour
false, // don't persist cookie
"" // roles
);
FormsAuthentication.SetAuthCookie(strUserName, false);
}
}

/// <summary>
/// 域验证
/// </summary>
/// <param name="AstrDomainName">域名称</param>
/// <param name="AstrDomainAccount">域账号</param>
/// <param name="AstrDomainPassword">域密码</param>
/// <returns></returns>
public bool ValidateUserAccount(string AstrDomainName, string AstrDomainAccount, string AstrDomainPassword)
{
const int LOGON32_LOGON_INTERACTIVE = 2; //通过网络验证账户合法性
const int LOGON32_PROVIDER_DEFAULT = 0; //使用默认的Windows 2000/NT NTLM验证方
IntPtr tokenHandle = new IntPtr(0);
tokenHandle = IntPtr.Zero;

string domainName = AstrDomainName; //域 如:officedomain
string domainAccount = AstrDomainAccount; //域帐号 如:administrator
string domainPassword = AstrDomainPassword;//密码
bool checkok = LogonUser(domainAccount, domainName, domainPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);

return checkok;
}
}

 

 

=======================================================================

其他参考代码 ===============================================================

=======================================================================

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);

bool isDomainUser = currentPrincipal.IsInRole("Domain Users");
isDomainUser=true; //为域用户

string userName=System.Environment.UserName;  //获取计算机登录名称

string computerName=System.Environment.MachineName;//获取计算机名称

string computerName=Dns.GetHostName();

posted @ 2016-07-11 14:16  chengeng  阅读(2353)  评论(0编辑  收藏  举报