Transfer: Using Impersonation in ASP. NET Applications)

Source: Internet
Author: User
Abstract By default, ASP. NET applications run with the local ASPNET account. This account is a common user group and has limited permissions to ensure the security of ASP. NET applications. But sometimes an ASP.. NET applications or programs that require specific permissions to execute a code segment, such as access to a file, in this case, you need to grant the account permission to the program or a specific code segment to execute the operation. This method is called impersonation ). This article describes several methods for using identity simulation in ASP. NET applications, and compares their applicability. Before reading this article, we recommend that you read the article: Identity Authentication in ASP. NET:. Net Security Guide to have a general understanding of ASP. NET security control. Directory
  • Identity simulation in ASP. NET
  • Simulate an IIS Authentication account
  • Simulate a specified user account in an ASP. NET application
  • Simulate an IIS Authentication account in the code
  • Simulate a specified user account in the code
  • More information
ASP. net identity simulation ASP. net implements identity authentication by using the Identity Authentication provider. In general, Asp.. Net authentication providers include form authentication, Windows authentication, and passport authentication. After Authentication, ASP. NET checks whether identity simulation is enabled. If enabled, ASP. NET applications use the client identity to selectively execute the application as the client identity. Otherwise, ASP. NET applications run with the local identity (typically using the local ASPNET account). The specific process is shown in:

Identity simulation is generally used for resource access control in ASP. NET applications, mainly including the following methods:

  • Simulate an IIS Authentication account
  • Simulate a specified user account in an ASP. NET application
  • Simulate an IIS Authentication account in the code
  • Simulate a specified user account in the code
Simulating an IIS authenticated account is the easiest way to use an IIS authenticated account to execute an application. You need to add the <identity> flag to the Web. config file and set the impersonate attribute to true:
<identity impersonate="true" />
In this case, the user identity authentication is sent to IIS. When anonymous logon is allowed, IIS submits an identity used for anonymous logon (IUSR_machinename by default) to the ASP. NET application. If anonymous logon is not allowed, IIS will pass the authenticated identity to the ASP. NET application. The specific access permissions of ASP. NET are determined by the permissions of this account. Simulate a specified user account. When an ASP. NET application needs to be executed with a specific user account, you can specify a specific user account in the <identity> mark of the web. config file:
<identity impersonate="true" userName="accountname" password="password" />
All requests on all pages of the ASP. NET application are executed with the specified user account permission. Simulating an IIS Authentication account in the Code makes it more flexible to use identity simulation in the Code. You can use identity simulation in a specified code segment to resume the use of an ASPNET local account outside the code segment. This method requires that the Windows Authentication Id be used. The following example simulates the IIS Authentication account in the Code: Visual Basic. NET
Dim impersonationContext As System.Security.Principal.WindowsImpersonationContextDim currentWindowsIdentity As System.Security.Principal.WindowsIdentitycurrentWindowsIdentity = 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();
Simulate a specified user account in the Code. The following example simulates a specified user account in the 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  = 2Dim LOGON32_PROVIDER_DEFAULT As Integer = 0Dim impersonationContext As WindowsImpersonationContextDeclare Auto Function LogonUser 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 IntegerDeclare Auto Function DuplicateToken Lib "advapi32.dll"(ByVal ExistingTokenHandle As IntPtr, _                           ImpersonationLevel As Integer, _                           ByRef DuplicateTokenHandle As IntPtr) As IntegerPublic Sub Page_Load(s As Object, 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      'Your impersonation failed. Therefore, include a fail-safe mechanism here.   End IfEnd SubPrivate Function impersonateValidUser(userName As String, _domain As String, password As String) As Boolean    Dim tempWindowsIdentity As WindowsIdentity   Dim token As IntPtr   Dim tokenDuplicate As IntPtr   If LogonUser(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 impersonationContext Is Nothing Then                   impersonateValidUser = False                Else               impersonateValidUser = True                End If      Else        impersonateValidUser = False      End If   Else      impersonateValidUser = False   End IfEnd FunctionPrivate 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", CharSet=CharSet.Auto)]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);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 mechanism here.   }}private bool impersonateValidUser(String userName, String domain, String password){   WindowsIdentity tempWindowsIdentity;   IntPtr token = IntPtr.Zero;   IntPtr tokenDuplicate = IntPtr.Zero;   if(LogonUser(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)            return true;         else            return false;       }      else         return false;   }    else      return false;}private void undoImpersonation(){     impersonationContext.Undo();} </script>
The following describes a simple application that uses identity simulation in ASP. NET applications. For example, an ASP. NET application needs to check whether a file on the server exists. The corresponding program code is:
bool a = File.Exists("D:\\Share\\test.txt");
By default, this ASP. NET application runs with an ASPNET account. For the sake of security, the ASPNET account does not have the access permission for the Directory D: \ Share \ on the server side. Without Identity simulation, because ASP. NET applications do not have the permission to access this directory, the returned value of File. Exists is always false regardless of whether the File Exists. To solve this problem, you can create another user account: FileExist and grant the account D: \ Share \ directory access permission. Then, specify the specific user account in the <identity> tag of the Web. config file of the application:
<identity impersonate="true" userName="FileExist" password="password" />
To run the program. From: http://www.microsoft.com/china/community/program/originalarticles/techdoc/impersonation.mspx
Related Article

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.