ASP.NET:模仿对在VMWare域 [英] ASP.NET: Impersonate against a domain on VMWare

查看:147
本文介绍了ASP.NET:模仿对在VMWare域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对自己冒充为在VMWare计算机上运行的ASP.NET应用程序的域用户。由于VMware虚拟机本身不是域中,ASP.NET无法解析用户令牌(在web.config中指定)。有没有办法做到这一点?

I need to impersonate myself as a domain user in a ASP.NET application running on VMWare machine. Since the VMWare machine is not itself in the domain, ASP.NET is unable to resolve the user token (specified in web.config). Is there a way to do that?

在此先感谢,
切赫

Thanks in advance, Petr

推荐答案

我使用这个类我写的所有的时间和它的工作原理就像一个魅力!

I use this class I wrote all the time and it works like a charm!

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
}

然后从客户端类调用它:

Then you call it from the client class as:

//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();
    		}
}

祝您好运!

这篇关于ASP.NET:模仿对在VMWare域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆