在ASP.NET中使用WINDOWS身份假冒

假冒用户的方法:
说明:在用ASP.NET时常因为安全问题而没有权限做某事,但有时我们又确实要使用到这些权限时,我们就应该给这些用户授予一些权限,而下面我们就来使用假冒来授予权限.

下面的是 IDEN.cs

using System;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace com.todayisp.identity
{
 /// <summary>
 /// IDEN 的摘要说明。
 /// </summary>
 ///
 

 public class IDEN
 {
  public const int LOGON32_LOGON_INTERACTIVE = 2;
  public const int LOGON32_PROVIDER_DEFAULT = 0;
  public const string ComputerName="localhost";
  WindowsImpersonationContext impersonationContext;

  [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
  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);

  //登入假冒用户
  //CompName是该计算机的用户名,CompPassword是该用户的密码
  public bool ChangeRoleIN(string CompName,string CompPassword)
  {
   try
   {
    if(CompName == null) return false;
    if(CompPassword == null) return false;

    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;
    
    if(LogonUser(CompName,ComputerName,CompPassword, 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;
    }
   }
   catch
   {
    return false;
   }
   
  }

  //登出假冒用户
  public void ChangeRoleOUT()
  {
   try
   {
    impersonationContext.Undo();
   }
   catch{}
  }
 }
}


使用方法,下面的是ASP.NET文件 ChangeUser.aspx

<%@ Page language="c#" AutoEventWireup="false"%>
<%@ Import Namespace= "com.todayisp.identity"%>//记得使用该命名空间
<%
string UserName = Request.Params["UserName"];
string Password = Request.Params["Password"];
if (UserName == null && Password == null)
{
 Response.Write("error:用户名和密码为空.");
 return;
}

//假冒身份开始
  IDEN Identity = new IDEN();
  bool In = Identity.ChangeRoleIN(UserName,PasswordKey);
  if (!In){
   Response.Write("error:变更用户权限失败");
   return;

//假冒身份结束
  Identity.ChangeRoleOUT();

%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值