CSDN博客

img keenx

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

发表于2004/6/22 21:14:00  888人阅读

假冒用户的方法:
说明:在用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();

%>

阅读全文
0 0

相关文章推荐

img
取 消
img