在ASP.Net中模拟新的用户身份

 前些日子在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, 30ref 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用户权限的限制。不过不要怪我没有提醒,你要保证这段代码里的安全性,以及模拟用户的帐号的密码管理
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值