To saucer(思归, .NET MVP) :如何在ASP.NET中取到AD用户,急死了
我按照你建议的方法用了伪装,可是却总是伪装不成功,帮忙看看吧,急死了
代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using EBudgetLib;
namespace EBudgetWeb.UserPower
{
/// <summary>
/// UserAccount 的摘要说明。
/// </summary>
public class UserAccount : System.Web.UI.Page
{
protected System.Web.UI.WebControls.ListBox ListBoxADUser;
protected System.Web.UI.WebControls.LinkButton LinkButtonToRight;
protected System.Web.UI.WebControls.LinkButton LinkButtonToLeft;
protected System.Web.UI.WebControls.ListBox ListBoxSelectUser;
protected System.Web.UI.WebControls.TextBox tbUserName;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto,
SetLastError=true)]
public extern static int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
private void Page_Load(object sender, System.EventArgs e)
{
if(impersonateValidUser("UserName", "DomainName", "UserPwd"))
{
string[] strDomainUser = EBudgetLib.CGetDomainUser.GetDomainUser();
undoImpersonation();
}
else
{
}
}
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
private void undoImpersonation()
{
impersonationContext.Undo();
}