asp.net(C#)中实现身份模拟(转贴)

asp.net(C#)中实现身份模拟
 
在一些应用场景中,需要以较高的帐户权限来执行一段程序从而实现某个功能。比如:在 ASP.NET 程序中,如果需要写入一段日志到文件中,但空间提供商并没有给指定目录 asp.net 帐户写权限,就可以用到此方法了,前提是你要知道他们给你开的用户及密码,一般都是 FTP 帐号及密码。当然,最简单的办法就是找空间商开通此权限。上面的情况可能不是必须这样做的,但以编程方法实现身份模拟的方法还是很有的!
代码如下:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace FCMS.Framework.Utility
{
///
/// Windows
身份模拟。
///
public class IdentityAnalogue {
//
模拟指定用户时使用的常量定义
/**
///
///
public co
nst int LOGON32_LOGON_INTERACTIVE = 2;
/**
///
///
public const int LOGON32_PROVIDER_DEFAULT = 0;
/**
///
///
WindowsImpersonationContext impersonationContext;
//win32api 引用
/** mmary>
///
///
///
///
///
///
///
///
///
[DllImport("advapi32.dll")]
public static extern int LogonUserA(string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/**
///
///
///
///
///
///
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
/**
///
///
///
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
public static extern bool RevertToSelf();
/**
///
///
///
///
[DllImport("kernel32.dll",CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
/**
///
///
public IdentityAnalogue() {
}


//
模拟指定的用户身份
/**
///
///
///
///
/// ram>
///
public bool ImpersonateValidUser(string userName,string domain,string password) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if(RevertToSelf()) {
if(LogonUserA(userName,domain,password,2,0,ref token)!=0) {
if(DuplicateToken(token,2,ref tokenDuplicate)!=0) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if(impersonationContext!=null) {
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token!= IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
// 取消模拟
/**
///
///
public void UndoImpersonation() {
impersonationContext.Undo();
}
}
}
使用方法:
// 在你执行特定功能的代码前先验证模拟帐户:
FCMS.Framework.Utility.IdentityAnalogue ia = new FCMS.Framework.Utility.Iden
tityAnalogue();
if( ia.ImpersonateValidUser( userName , domain , password ) ){
//
执行特定功能的代码段,参数 domain 可为空 ""
}
//
最后将用户上下文恢复为当前表示的 Windows 用户
ia.UndoImpersonation()
;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值