Domanda

C'è una semplice scatola modo di impersonare un utente .NET?

Finora ho usato questa classe dal progetto di codice per tutti i miei rappresentazione requisiti.

C'è un modo migliore per farlo .NET Framework?

Ho un utente insieme di credenziali, (username, password, nome del dominio), che rappresenta l'identità di cui ho bisogno per rappresentare.

È stato utile?

Soluzione

Ecco una buona panoramica dei concetti di rappresentazione di .NET.

Fondamentalmente userete queste classi che sono pronte all'uso nel framework .NET:

Il codice può spesso essere lungo ma è per questo che vedi molti esempi come quello a cui fai riferimento che cercano di semplificare il processo.

Altri suggerimenti

"Rappresentazione" in .Lo spazio in rete in genere significa che il codice in esecuzione in un account utente specifico.E 'un po' di separare concetto di ottenere l'accesso a tale account utente tramite username e password, anche se queste due idee coppia insieme di frequente.Mi limiterò a descrivere entrambi, e poi spiegare come usare il mio SimpleImpersonation la biblioteca, che li utilizza internamente.

La rappresentazione

Le Api per la rappresentazione sono forniti in .Rete tramite il System.Security.Principal spazio dei nomi:

  • Codice più recente (.NETTO di 4,6+, .NET Core, etc.) in genere necessario utilizzare WindowsIdentity.RunImpersonated, che accetta un handle per il token dell'account utente e, quindi, un Action o Func<T> per il codice da eseguire.

    WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    o

    var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • Precedente codice utilizzato il WindowsIdentity.Impersonate metodo per recuperare un WindowsImpersonationContext oggetto.Questo oggetto implementa IDisposable, quindi in genere dovrebbe essere chiamato da un using il blocco.

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
    {
        // do whatever you want as this user.
    }
    

    Mentre questa API esiste ancora nel .NET Framework, deve essere generalmente evitato, e non è disponibile in .NET Core o .NET Standard.

L'accesso all'Account Utente

Le API per l'utilizzo di un nome utente e una password per ottenere l'accesso a un account utente in Windows è LogonUser - che è un nativo Win32 API.Non esiste attualmente un built-in .NET API per la chiamata di esso, quindi, si deve ricorrere a P/Invoke.

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

Questa è la chiamata di base definizione, tuttavia c'è molto di più da considerare per l'utilizzo in produzione:

  • Ottenere una maniglia con la "cassaforte" pattern di accesso.
  • Chiusura nativo gestisce in modo appropriato
  • Protezione dall'accesso di codice (CAS) livelli di fiducia (in .NET Framework)
  • Passando SecureString quando è possibile raccogliere una sicura via di utente battiture.

La quantità di codice da scrivere per illustrare tutto questo è al di là di quello che dovrebbe essere in un StackOverflow risposta, IMHO.

Un Combinato e di più Facile Approccio

Invece di scrivere tutto da soli, prendere in considerazione utilizzando il mio SimpleImpersonation la biblioteca, che unisce la rappresentazione e l'accesso degli utenti in una singola API.Funziona bene sia moderna e basi di codice, con la stessa semplice API:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
}); 

o

var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
    return something;
});

Notare che è molto simile al WindowsIdentity.RunImpersonated API, ma non richiede che si sa nulla di token maniglie.

Questo è l'API della versione 3.0.0.Vedere il file leggimi per ulteriori dettagli.Si noti inoltre che una precedente versione della libreria utilizzata un'API con il IDisposable modello, simile a WindowsIdentity.Impersonate.La nuova versione è molto più sicuro, e sono entrambi utilizzati internamente.

Questo è probabilmente quello che vuoi:

using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
     //your code goes here
}

Ma ho davvero bisogno di maggiori dettagli per aiutarti. È possibile eseguire la rappresentazione con un file di configurazione (se si sta tentando di farlo su un sito Web) o tramite decoratori di metodi (attributi) se si tratta di un servizio WCF o tramite ... si ottiene l'idea.

Inoltre, se stiamo parlando di impersonare un client che ha chiamato un determinato servizio (o app Web), è necessario configurare il client correttamente in modo che passi i token appropriati.

Infine, se ciò che vuoi veramente fare è Delegare, devi anche impostare AD correttamente in modo che gli utenti e le macchine siano affidabili per la delega.

Modifica
Dai un'occhiata a qui per vedere come impersonare un altro utente e per ulteriore documentazione.

Ecco la mia porta vb.net della risposta di Matt Johnson. Ho aggiunto un enum per i tipi di accesso. LOGON32_LOGON_INTERACTIVE è stato il primo valore enum che ha funzionato per il server sql. La mia stringa di connessione era solo attendibile. Nessun nome utente / password nella stringa di connessione.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <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 operations; 
      ''' therefore, it is 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 plaintext 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. This type is also for higher performance servers that process many plaintext
      ''' 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 for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' 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 identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

È necessario utilizzare con un'istruzione Using per contenere del codice da eseguire impersonati.

Visualizza maggiori dettagli dalla mia risposta precedente Ho creato un pacchetto nuget Nuget

Codice su Github

esempio: puoi usare:

           string login = "";
           string domain = "";
           string password = "";

           using (UserImpersonation user = new UserImpersonation(login, domain, password))
           {
               if (user.ImpersonateValidUser())
               {
                   File.WriteAllText("test.txt", "your text");
                   Console.WriteLine("File writed");
               }
               else
               {
                   Console.WriteLine("User not connected");
               }
           }

Vieuw il codice completo:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;


/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
    /// <summary>
    /// Logon method (check athetification) from advapi32.dll
    /// </summary>
    /// <param name="lpszUserName"></param>
    /// <param name="lpszDomain"></param>
    /// <param name="lpszPassword"></param>
    /// <param name="dwLogonType"></param>
    /// <param name="dwLogonProvider"></param>
    /// <param name="phToken"></param>
    /// <returns></returns>
    [DllImport("advapi32.dll")]
    private static extern bool LogonUser(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

    /// <summary>
    /// Close
    /// </summary>
    /// <param name="handle"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    private WindowsImpersonationContext _windowsImpersonationContext;
    private IntPtr _tokenHandle;
    private string _userName;
    private string _domain;
    private string _passWord;

    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_INTERACTIVE = 2;

    /// <summary>
    /// Initialize a UserImpersonation
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="passWord"></param>
    public UserImpersonation(string userName, string domain, string passWord)
    {
        _userName = userName;
        _domain = domain;
        _passWord = passWord;
    }

    /// <summary>
    /// Valiate the user inforamtion
    /// </summary>
    /// <returns></returns>
    public bool ImpersonateValidUser()
    {
        bool returnValue = LogonUser(_userName, _domain, _passWord,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref _tokenHandle);

        if (false == returnValue)
        {
            return false;
        }

        WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
        _windowsImpersonationContext = newId.Impersonate();
        return true;
    }

    #region IDisposable Members

    /// <summary>
    /// Dispose the UserImpersonation connection
    /// </summary>
    public void Dispose()
    {
        if (_windowsImpersonationContext != null)
            _windowsImpersonationContext.Undo();
        if (_tokenHandle != IntPtr.Zero)
            CloseHandle(_tokenHandle);
    }

    #endregion
}

Sono consapevole di essere in ritardo per la festa, ma ritengo che la biblioteca di Phillip Allan-Harding , è il migliore per questo caso e simili.

Hai solo bisogno di un piccolo pezzo di codice come questo:

private const string LOGIN = "mamy";
private const string DOMAIN = "mongo";
private const string PASSWORD = "HelloMongo2017";

private void DBConnection()
{
    using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
    {
    }
}

E aggiungi la sua classe:

. Rappresentazione NET (C #) con credenziali di rete

Il mio esempio può essere utilizzato se è necessario che l'accesso impersonato disponga di credenziali di rete, ma ha più opzioni.

Puoi usare questa soluzione. (Usa il pacchetto nuget) Il codice sorgente è disponibile su: Github: https://github.com/michelcedric/UserImpersonation

Più dettagli https: //michelcedric.wordpress. com / 2015/09/03 / usurpazione-didentite-dun-user-c-user-rappresentazione /

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top