前些日子在asp.net中创建IIS虚拟站点,总是失败,于是四处拜访名山,寻找名师,终于明白默认ASP.NET用户的执行权限不够。web.config中配置的<identity impersonate="true" username='' password=''/>也不起作用。
找到的一些代码,但用起来不太方便,于是自己写了一个类,来模拟新的用户身份.
/// <summary>
/// Impersonate the specified account
/// </summary>
public
class
Impersonator : IDisposable
{
[DllImport("C:/Windows/System32/advapi32.dll")]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType,
int dwLogonProvider, ref int phToken);

[DllImport("C:/Windows/System32/Kernel32.dll")]
public static extern int GetLastError();

private WindowsImpersonationContext impersonatingContext = null;

/// <summary>
/// Logon with specified account
/// </summary>
/// <param name="domain"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public void Logon(string domain, string username, string password)
{
int token1 = 0;
bool loggedOn = LogonUser(username, domain, password, 3, 0, ref token1);
int ret = GetLastError();
if (ret != 0)
{
throw new Exception("Error code (126 == "Specified module could not be found"): " + ret.ToString());
}
IntPtr token2 = new IntPtr(token1);
WindowsIdentity mWI2 = new WindowsIdentity(token2);
impersonatingContext = mWI2.Impersonate();
}

/// <summary>
/// Logoff the account
/// </summary>
public void Logoff()
{
if (impersonatingContext != null)
{
impersonatingContext.Undo();
impersonatingContext = null;
}
}

public void Dispose()
{
Logoff();
}
}
单元测试代码和使用方法如下:
[Test]
public
void
TestCase()
{
Assert.IsFalse("koy2000"==Environment.UserName);

Impersonator mock = new Impersonator();
mock.Logon("localhost","koy2000","koy2000");

Assert.IsTrue("koy2000" == Environment.UserName);

mock.Logoff();

Assert.IsFalse("koy2000" == Environment.UserName);
}
有了这个类以后,哈哈,就可以为所欲为了。不用担心asp.net用户权限的限制。不过不要怪我没有提醒,你要保证这段代码里的安全性,以及模拟用户的帐号的密码管理
找到的一些代码,但用起来不太方便,于是自己写了一个类,来模拟新的用户身份.





















































单元测试代码和使用方法如下:














有了这个类以后,哈哈,就可以为所欲为了。不用担心asp.net用户权限的限制。不过不要怪我没有提醒,你要保证这段代码里的安全性,以及模拟用户的帐号的密码管理