I have successfully used the windows program to successfully create a batch of domain accounts with mailboxes. However, when I hand over this code to a colleague (she is responsible for developing Web applications) migrate to Asp.. Net. Why?
We consulted Microsoft engineers and told us that this is because ASP.net has insufficient permissions. We should simulate users in asp.net so that they can be created successfully.
I will extract some articles from Microsoft:
Account or user simulating IIS Authentication
To receive ASP. when every request on each page in the. NET application simulates the Microsoft Internet Information Service (IIS) authentication user, the Web. the config file contains the <identity> flag and sets the impersonate attribute to true. For example:
<Identity impersonate = "true"/>
Simulate a specific user for all requests of ASP. NET Applications
To be ASP.. NET application. specify the userName and passWord attributes in the <identity> tag of the config file. For example:
<Identity impersonate = "true" userName = "accountname" password = "password"/>
Note: The process ID simulating a specific user on the thread must have the "as part of the operating system" permission. The aspnet_wp.exe process runs under a computer account named ASPNET. However, this account does not have the permissions required to simulate a specific user. If you try to simulate a specific user, an error message is displayed.
To solve this problem, use one of the following methods:
?
Grant the "as part of the operating system" permission to the ASPNET account (the account with the lowest permissions.
Note: although this method can solve the problem, Microsoft does not recommend this method.
?
In the <processModel> Configuration section of the Machine. config file, change the account used to run the Aspnet_wp.exe process to the System account.
Simulate user authentication in code
To simulate User Identity verification only when a specific part of the code is running, you can use the following code. This method requires that the type of the user identity for authentication be WindowsIdentity.
Visual Basic. NET
Dim impersonationContext As System. Security. Principal. WindowsImpersonationContext
Dim currentWindowsIdentity As System. Security. Principal. WindowsIdentity
CurrentWindowsIdentity = CType (User. Identity, System. Security. Principal. WindowsIdentity)
ImpersonationContext = currentWindowsIdentity. Impersonate ()
'Insert your code that runs under the security context of the authenticating user here.
ImpersonationContext. Undo ()
Visual C #. NET
System. Security. Principal. WindowsImpersonationContext impersonationContext;
ImpersonationContext =
(System. Security. Principal. WindowsIdentity) User. Identity). Impersonate ();
// Insert your code that runs under the security context of the authenticating user here.
ImpersonationContext. Undo ();
Visual J #. NET
System. Security. Principal. WindowsImpersonationContext impersonationContext;
ImpersonationContext =
(System. Security. Principal. WindowsIdentity) get_User (). get_Identity (). Impersonate ();
// Insert your code that runs under the security context of the authenticating user here.
ImpersonationContext. Undo ();
Simulate a specific user in the code
To simulate a specific user only when running a specific part of the code, use the following code:
Visual Basic. NET
<% @ Page Language = "VB" %>
<% @ Import Namespace = "System. Web" %>
<% @ Import Namespace = "System. Web. Security" %>
<% @ Import Namespace = "System. Security. Principal" %>
<% @ Import Namespace = "System. Runtime. InteropServices" %>
<Script runat = server>
Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
Dim LOGON32_PROVIDER_DEFAULT As Integer = 0
Dim impersonationContext As WindowsImpersonationContext
Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String ,_
ByVal lpszDomain As String ,_
ByVal lpszPassword As String ,_
ByVal dwLogonType As Integer ,_
ByVal dwLogonProvider As Integer ,_
ByRef phToken As IntPtr) As Integer
Declare Auto Function DuplicateToken Lib "advapi32.dll "(_
ByVal ExistingTokenHandle As IntPtr ,_
ByVal ImpersonationLevel As Integer ,_
ByRef DuplicateTokenHandle As IntPtr) As Integer
Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
Public Sub Page_Load (ByVal s As Object, ByVal e As EventArgs)
If impersonateValidUser ("username", "domain", "password") Then
'Insert your code that runs under the security context of a specific user here.
UndoImpersonation ()
Else
'Ur impersonation failed. Therefore, include a fail-safe mechanic here.
End If
End Sub
Private Function impersonateValidUser (ByVal userName As String ,_
ByVal domain As String, ByVal password As String) As Boolean
Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr. Zero
Dim tokenDuplicate As IntPtr = IntPtr. Zero
ImpersonateValidUser = False
If RevertToSelf () Then
If LogonUserA (userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken (token, 2, tokenDuplicate) <> 0 Then
TempWindowsIdentity = New WindowsIdentity (tokenDuplicate)
ImpersonationContext = tempWindowsIdentity. Impersonate ()
If Not impersonationContext Is Nothing Then
ImpersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate. Equals (IntPtr. Zero) Then
CloseHandle (tokenDuplicate)
End If
If Not token. Equals (IntPtr. Zero) Then
CloseHandle (token)
End If
End Function
Private Sub undoImpersonation ()
ImpersonationContext. Undo ()
End Sub
</Script>
Visual C #. NET
<% @ Page Language = "C #" %>
<% @ Import Namespace = "System. Web" %>
<% @ Import Namespace = "System. Web. Security" %>
<% @ Import Namespace = "System. Security. Principal" %>
<% @ Import Namespace = "System. Runtime. InteropServices" %>
<Script runat = server>
Public const int LOGON32_LOGON_INTERACTIVE = 2;
Public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[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 void Page_Load (Object s, EventArgs e)
{
If (impersonateValidUser ("username", "domain", "password "))
{
// Insert your code that runs under the security context of a specific user here.
UndoImpersonation ();
}
Else
{
// Your impersonation failed. Therefore, include a fail-safe mechanic here.
}
}
Private 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, 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)
{
CloseHandle (token );
CloseHandle (tokenDuplicate );
Return true;
}
}
}
}
If (token! = IntPtr. Zero)
CloseHandle (token );
If (tokenDuplicate! = IntPtr. Zero)
CloseHandle (tokenDuplicate );
Return false;
}
Private void undoImpersonation ()
{
ImpersonationContext. Undo ();
}
</Script>
Visual J #. NET
<% @ Page language = "VJ #" %>
<% @ Import Namespace = "System. Web" %>
<% @ Import Namespace = "System. Web. Security" %>
<% @ Import Namespace = "System. Security. Principal" %>
<% @ Import Namespace = "System. Runtime. InteropServices" %>
<Script runat = server>
Public static int LOGON32_LOGON_INTERACTIVE = 2;
Public static int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
/** @ Attribute DllImport ("advapi32.dll ")*/
Public static native int LogonUserA (String lpszUserName,
String lpszDomain,
String lpszPassword,
Int dwLogonType,
Int dwLogonProvider,
System. IntPtr [] phToken );
/** @ Attribute DllImport ("advapi32.dll ",
CharSet = CharSet. Auto, SetLastError = true )*/
Public static native int DuplicateToken (System. IntPtr hToken,
Int impersonationLevel,
System. IntPtr [] hNewToken );
/** @ Attribute DllImport ("kernel32.dll", CharSet = CharSet. Auto )*/
Public static native boolean CloseHandle (System. IntPtr [] handle );
/** @ Attribute DllImport ("advapi32.dll ",
CharSet = CharSet. Auto, SetLastError = true )*/
Public static native boolean RevertToSelf ();
Public void Page_Load (Object s, System. EventArgs e)
{
If (impersonateValidUser ("username", "domain", "password "))
{
// Insert your code that runs under the security context of a specific user here.
UndoImpersonation ();
}
Else
{
// Your impersonation failed. Therefore, include a fail-safe mechanic here.
}
}
Private boolean impersonateValidUser (String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
System. IntPtr [] token = new System. IntPtr [1];
System. IntPtr [] tokenDuplicate = new System. IntPtr [1];
If (RevertToSelf ())
{
If (LogonUserA (userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, token )! = 0)
{
If (DuplicateToken (token [0], 2, tokenDuplicate )! = 0)
{
TempWindowsIdentity = new WindowsIdentity (tokenDuplicate [0]);
ImpersonationContext = tempWindowsIdentity. Impersonate ();
If (impersonationContext! = Null)
{
CloseHandle (tokenDuplicate );
CloseHandle (token );
Return true;
}
}
}
}
If (! Token [0]. Equals (System. IntPtr. Zero ))
CloseHandle (token );
If (! TokenDuplicate [0]. Equals (System. IntPtr. Zero ))
CloseHandle (tokenDuplicate );
Return false;
}
Private void undoImpersonation ()
{
ImpersonationContext. Undo ();
}
</Script>