Under. NET simulate different identities landing to get different permissions

Source: Internet
Author: User
Tags bool constructor error code log mail client
Whether it's ASP.net, Web Service, or window service, programs run with only partial permissions on the local computer, sometimes with more permissions, such as reading and writing to a server or file on one computer in a domain, which requires greater permissions, such as domain account permissions.

By capturing different identities of WindowsImpersonationContext objects, you can simulate different user login, see the Networksecurity class that I generated
public static WindowsImpersonationContext ImpersonateUser (String strdomain,
String Strlogin,

String Strpwd,

LogonType LogonType,

Logonprovider Logonprovider);

Attached NetworkSecurity.cs source code is as follows:

/*
* 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 to users who'll 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 are therefore
Inappropriate for some client/server applications, such as a mail server.
</summary>
Logon32_logon_interactive = 2,

<summary>
This logon type was intended for high performance servers to authenticate clear text passwords.
The LogonUser function does not cache credentials to this logon type.
</summary>
Logon32_logon_network = 3,

<summary>
This logon type was intended for batch servers where processes may was 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 to GINA DLLs logging on the users who'll be interactively using the computer.
This logon type allows a is a unique audit record to is generated that shows when the workstation is 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" to "connections to" network servers while impersonating the client.
This is allows a server to accept clear text credentials from a client, call LogonUser, and 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 it current token and specify new credentials
For outbound connections. The new logon session has the same local identity, but uses different credentials
For the other network connections.
This logon type was 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 your NULL for the domain name and
The user name is isn't 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 in to the local computer.
The local computer are the computer from which ImpersonateUser was called.
You are cannot use ImpersonateUser to log in to a remote computer.
You are 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 a token handle to impersonate the specified user, or in most,
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 for the ' user account ' password by specified
<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 is blank, assume local machine
if (Strdomain = "")
Strdomain = System.Environment.MachineName;

Try
{
const int securityimpersonation = 2;

Call LogonUser to obtain a handle to a 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 are 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);
}
}
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.