我需要冒充自己在VMWare计算机上运行的ASP.NET应用程序中的域用户。由于VMWare计算机本身不在域中,因此ASP.NET无法解析用户令牌(在web.config中指定)。有没有办法做到这一点?
提前致谢, 彼得
答案 0 :(得分:1)
我使用这个我一直写的课,它就像一个魅力!
using System;
using System.Security.Principal;
/// <summary>
/// Changes the security context the application runs under.
/// </summary>
public class ImpersonateHelper : IDisposable
{
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
private IntPtr _token = IntPtr.Zero;
private WindowsImpersonationContext _impersonatedUser = null;
public IntPtr Token
{
get { return _token; }
set { _token = value; }
}
public ImpersonateHelper(IntPtr token)
{
_token = token;
}
/// <summary>
/// Switch the user to that set by the Token property
/// </summary>
public void Impersonate()
{
if (_token == IntPtr.Zero)
_token = WindowsIdentity.GetCurrent().Token;
_impersonatedUser = WindowsIdentity.Impersonate(_token);
}
/// <summary>
/// Revert to the identity (user) before Impersonate() was called
/// </summary>
public void Undo()
{
if (_impersonatedUser != null)
_impersonatedUser.Undo();
}
#region IDisposable Members
private bool _isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
if (_impersonatedUser != null)
_impersonatedUser.Dispose();
}
CloseHandle(_token);
_token = IntPtr.Zero;
}
_isDisposed = true;
}
~ImpersonateHelper()
{
Dispose(false);
}
#endregion
}
然后从客户端类中将其称为:
//Run task as the impersonated user and not as NETWORKSERVICE or ASPNET (in IIS5)
try{
impersonate.Impersonate();
//Do work that needs to run as domain user here...
}
finally
{
//Revert impersonation to NETWORKSERVICE or ASPNET
if (impersonate != null)
{
impersonate.Undo();
impersonate.Dispose();
}
}
祝你好运!
答案 1 :(得分:-4)
这可能是一个愚蠢的明显答案,但您可以将VMWare计算机添加到域中。