分享
 
 
 

.net下模拟不同身份登陆以获取不同权限" (.net刚上手就遇到一个难题,解决之,爽)

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

不管是asp.net、web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限。

通过获取不同身份的WindowsImpersonationContext对象,可以模拟不同用户登陆,请看我生成的NetworkSecurity类的

public static WindowsImpersonationContext ImpersonateUser(string strDomain,

string strLogin,

string strPwd,

LogonType logonType,

LogonProvider logonProvider);

附NetworkSecurity.cs源代码如下:

/*

* Author : TongWei

* Date : 2005-1-25

* Rights : China Netwave Inc.@2005

*/

using System;

using System.Runtime.InteropServices;

using System.Security.Principal;

using System.Security.Permissions;

namespace CNW.OMP.Common.Utility

{

public enum LogonType : int

{

/// <summary>

/// This logon type is intended for users who will be interactively using the computer, such as a user

/// being logged on by a terminal server, remote shell, or similar process. This logon type has the

/// additional expense of caching logon information for disconnected operation, and is therefore

/// inappropriate for some client/server applications, such as a mail server.

/// </summary>

LOGON32_LOGON_INTERACTIVE = 2,

/// <summary>

/// This logon type is intended for high performance servers to authenticate clear text passwords.

/// The LogonUser function does not cache credentials for this logon type.

/// </summary>

LOGON32_LOGON_NETWORK = 3,

/// <summary>

/// This logon type is intended for batch servers, where processes may be executing on behalf of a user

/// without their direct intervention; or for higher performance servers that process many clear-text

/// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache

/// credentials for this logon type.

/// </summary>

LOGON32_LOGON_BATCH = 4,

/// <summary>

/// Indicates a service-type logon. The account provided must have the service privilege enabled.

/// </summary>

LOGON32_LOGON_SERVICE = 5,

/// <summary>

/// This logon type is intended for GINA DLLs logging on users who will be interactively using the computer.

/// This logon type allows a unique audit record to be generated that shows when the workstation was unlocked.

/// </summary>

LOGON32_LOGON_UNLOCK = 7,

/// <summary>

/// Windows XP/2000: This logon type preserves the name and password in the authentication packages,

/// allowing the server to make connections to other network servers while impersonating the client.

/// This allows a server to accept clear text credentials from a client, call LogonUser, verify that

/// the user can access the system across the network, and still communicate with other servers.

/// </summary>

LOGON32_LOGON_NETWORK_CLEARTEXT = 8,

/// <summary>

/// Windows XP/2000: This logon type allows the caller to clone its current token and specify new credentials

/// for outbound connections. The new logon session has the same local identity, but uses different credentials

/// for other network connections.

/// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.

/// </summary>

LOGON32_LOGON_NEW_CREDENTIALS = 9

};

public enum LogonProvider : int

{

/// <summary>

/// Use the standard logon provider for the system. The default security provider is NTLM.

/// Windows XP: The default provider is negotiate, unless you pass NULL for the domain name and

/// the user name is not in UPN format. In this case the default provider is NTLM.

/// </summary>

LOGON32_PROVIDER_DEFAULT = 0,

/// <summary>

/// Use the Windows NT 3.5 logon provider.

/// </summary>

LOGON32_PROVIDER_WINNT35 = 1,

/// <summary>

/// Use the NTLM logon provider.

/// </summary>

LOGON32_PROVIDER_WINNT40 = 2,

/// <summary>

/// Windows XP/2000: Use the negotiate logon provider.

/// </summary>

LOGON32_PROVIDER_WINNT50 = 3

};

class SecuUtil32

{

[DllImport("advapi32.dll", SetLastError=true)]

public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,

int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]

public extern static bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]

public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,

int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

}

public class NetworkSecurity

{

public NetworkSecurity()

{

//

// TODO: Add constructor logic here

//

}

/// <summary>

/// The ImpersonateUser function attempts to log a user on to the local computer.

/// The local computer is the computer from which ImpersonateUser was called.

/// You cannot use ImpersonateUser to log on to a remote computer.

/// You specify the user with a user name and domain, and authenticate the user with a clear-text password.

/// If the function succeeds, you receive a handle to a token that represents the logged-on user.

/// You can then use this token handle to impersonate the specified user, or in most cases,

/// to create a process running in the context of the specified user.

/// </summary>

/// <param name="strDomain">

/// specifies the name of the domain or server whose account database contains the strLogin account.

/// </param>

/// <param name="strLogin">specifies the name of the user.</param>

/// <param name="strPwd">specifies the clear-text password for the user account specified by strLogin.</param>

/// <param name="logonType">Specifies the type of logon operation to perform.</param>

/// <param name="logonProvider">Specifies the logon provider.</param>

/// <example>

/// //Add System.Security.dll

/// //using System.Security.Principal;

///

/// string strDomain=ConfigurationSettings.AppSettings["mSALoginDomainName"];

/// string strUser=ConfigurationSettings.AppSettings["mSALoginDomainUser"];

/// string strPassword=ConfigurationSettings.AppSettings["mSALoginDomainPassword"];

///

/// WindowsImpersonationContext impContext = null;

/// try

/// {

/// impContext = NetworkSecurity.ImpersonateUser(strDomain,strUser,strPassword,

/// LogonType.LOGON32_LOGON_SERVICE,

/// LogonProvider.LOGON32_PROVIDER_DEFAULT);

/// }

/// catch

/// {

///

/// }

///

/// //work under this logined user

///

/// impContext.Undo();

/// </example>

/// <returns>

/// </returns>

public static WindowsImpersonationContext ImpersonateUser(string strDomain,

string strLogin,

string strPwd,

LogonType logonType,

LogonProvider logonProvider)

{

// Initialize tokens

IntPtr tokenHandle = new IntPtr(0);

IntPtr dupeTokenHandle = new IntPtr(0);

tokenHandle = IntPtr.Zero;

dupeTokenHandle = IntPtr.Zero;

// If domain name was blank, assume local machine

if (strDomain == "")

strDomain = System.Environment.MachineName;

try

{

const int SecurityImpersonation = 2;

// Call LogonUser to obtain a handle to an access token.

bool returnValue = SecuUtil32.LogonUser(

strLogin,

strDomain,

strPwd,

(int)logonType,

(int)logonProvider,

ref tokenHandle);

// Did impersonation fail?

if (false == returnValue)

{

int ret = Marshal.GetLastWin32Error();

// Throw the exception show the reason why LogonUser failed

string strErr = String.Format("LogonUser failed with error code : {0}", ret);

throw new ApplicationException(strErr, null);

}

// Get identity before impersonation

bool retVal = SecuUtil32.DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);

// Did DuplicateToken fail?

if (false == retVal)

{

// Close existing handle

SecuUtil32.CloseHandle(tokenHandle);

// Throw the exception show the reason why DuplicateToken failed

throw new ApplicationException("Failed to duplicate token", null);

}

// Create new identity using new primary token

// The token that is passed to the following constructor must

// be a primary token in order to use it for impersonation.

WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);

WindowsImpersonationContext impersonatedUser = newId.Impersonate();

return impersonatedUser;

}

catch (Exception ex)

{

throw new ApplicationException(ex.Message, ex);

}

finally

{

// Close handle

if (tokenHandle != IntPtr.Zero)

SecuUtil32.CloseHandle(tokenHandle);

if (dupeTokenHandle != IntPtr.Zero)

SecuUtil32.CloseHandle(dupeTokenHandle);

}

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有