1.利用DirectoryEntry模拟域帐号登录
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td>用户名:</td> <td> <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> </td> </tr> <tr> <td>密码:</td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td>域:</td> <td> <asp:DropDownList ID="ddlDomain" runat="server"> <asp:ListItem Value="TestDomain">TestDomain</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td align="center" colspan="2"> <asp:Button ID="btnLogin" runat="server" Text="登录" onclick="btnLogin_Click" /></td> </tr> </table> <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label> </div> </form> </body> </html>
后台代码:
protected void btnLogin_Click(object sender, EventArgs e) { try { using (DirectoryEntry deUser = new DirectoryEntry(@"LDAP://" + ddlDomain.SelectedValue, txtUserName.Text.Trim(),txtPassword.Text.Trim())) { DirectorySearcher src = new DirectorySearcher(deUser); //src.Filter = ("(objectClass=user)"); src.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName="+txtUserName.Text.Trim()+"))"; src.PropertiesToLoad.Add("cn"); src.SearchRoot = deUser; src.SearchScope = SearchScope.Subtree; SearchResult result = src.FindOne(); if (result != null)//登录成功 { DirectoryEntry de = result.GetDirectoryEntry(); foreach (var p in de.Properties.PropertyNames) { lblMsg.Text+=p.ToString() + ":" + de.Properties[p.ToString()][0].ToString() + "<br/>"; } } else { Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script language=\"javascript\">alert('用户名或密码错误!')</script>"); } } } catch (Exception exc) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script language=\"javascript\">alert('"+exc.Message+"')</script>"); } }
2.利用API模拟域帐号登录
[DllImport("advapi32.DLL", SetLastError = true)] public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); protected void Page_Load(object sender, EventArgs e) { IntPtr admin_token = default(IntPtr); WindowsIdentity wid_admin = null; WindowsImpersonationContext wic = null; //在程序中模拟域帐户登录 if (LogonUser("ultimus", "valmont-as", "Valmont23", 9, 0, ref admin_token) != 0) { using (wid_admin = new WindowsIdentity(admin_token)) { using (wic = wid_admin.Impersonate()) { } } } }