Implementare la rappresentazione in un'applicazione ASP.NET

Questo articolo descrive diversi modi per implementare la rappresentazione in un'applicazione ASP.NET.

Versione originale del prodotto: ASP.NET
Numero KB originale: 306158

Riepilogo

Questo articolo illustra come implementare la rappresentazione modificando il file Web.config ed eseguendo una particolare sezione di codice.

Fa riferimento agli spazi dei nomi della libreria di classi di Microsoft .NET Framework seguenti:

  • System.Web.Security
  • System.Security.Principal
  • System.Runtime.InteropServices

È possibile usare il codice seguente per determinare quale utente viene eseguito dal thread:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

Rappresentare l'account o l'utente autenticato di IIS

Per rappresentare l'utente di autenticazione di Internet Information Services (IIS) in ogni richiesta per ogni pagina di un'applicazione ASP.NET, è necessario includere un <identity> tag nel file di Web.config di questa applicazione e impostare l'attributo di rappresentazione su true. Ad esempio:

<identity impersonate="true" />

Rappresentare un utente specifico per tutte le richieste di un'applicazione ASP.NET

Per rappresentare un utente specifico per tutte le richieste in tutte le pagine di un'applicazione ASP.NET, è possibile specificare gli userName attributi e password nel <identity> tag del file Web.config per l'applicazione. Ad esempio:

<identity impersonate="true" userName="accountname" password="password" />

Nota

L'identità del processo che rappresenta un utente specifico in un thread deve disporre di Act come parte del privilegio del sistema operativo . Per impostazione predefinita, il processo di Aspnet_wp.exe viene eseguito con un account computer denominato ASPNET. Tuttavia, questo account non dispone dei privilegi necessari per rappresentare un utente specifico. Se si tenta di rappresentare un utente specifico, viene visualizzato un messaggio di errore. Queste informazioni si applicano solo a .NET Framework 1.0. Questo privilegio non è necessario per .NET Framework 1.1.

Per risolvere questo problema, usare uno dei metodi seguenti:

  • Concedere l'act come parte del privilegio del sistema operativo all'account ASPNET (l'account con privilegi minimi).

    Nota

    Anche se è possibile usare questo metodo per risolvere il problema, Microsoft non consiglia questo metodo.

  • Modificare l'account in cui viene eseguito il processo di Aspnet_wp.exe nell'account di sistema nella <processModel> sezione di configurazione del file Machine.config.

Rappresentare l'utente che esegue l'autenticazione nel codice

Per rappresentare l'utente di autenticazione (User.Identity) solo quando si esegue una particolare sezione di codice, è possibile usare il codice da seguire. Questo metodo richiede che l'identità utente di autenticazione sia di tipo 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();
    

Rappresentare un utente specifico nel codice

Per rappresentare un utente specifico solo quando si esegue una particolare sezione di codice, usare il codice seguente:

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
         'Your impersonation failed. Therefore, include a fail-safe mechanism 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 mechanism 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>

Se il processo di Aspnet_wp.exe è in esecuzione in un computer basato su Windows 2000, l'identità del processo che rappresenta un utente specifico in un thread deve avere l'opzione Act come parte del privilegio del sistema operativo . L'azione come parte del privilegio del sistema operativo non è necessaria se il processo di Aspnet_wp.exe è in esecuzione in un computer basato su Windows XP o in un computer basato su Windows Server 2003. Per impostazione predefinita, il processo di Aspnet_wp.exe viene eseguito con un account computer denominato ASPNET. Tuttavia, questo account non dispone dei privilegi necessari per rappresentare un utente specifico. Se si tenta di rappresentare un utente specifico, viene visualizzato un messaggio di errore.

Per risolvere questo problema, usare uno dei metodi seguenti:

  • Concedere l'act come parte del privilegio del sistema operativo all'account ASPNET.

    Nota

    Questo metodo non è consigliabile per risolvere il problema.

  • Modificare l'account in cui viene eseguito il processo di Aspnet_wp.exe nell'account di sistema nella <processModel> sezione di configurazione del file Machine.config.

Riferimenti

panoramica della sicurezza ASP.NET