Existe-t-il un moyen simple d’usurper l’identité d’un utilisateur dans .NET?
Jusqu’à présent, j’ai utilisé cette classe à partir de projet de code pour toutes mes exigences d’identité.
Existe-t-il un meilleur moyen de le faire en utilisant .NET Framework?
J’ai un ensemble d’informations d’identification d’utilisateur (nom d’utilisateur, mot de passe, nom de domaine) qui représente l’identité que je dois emprunter.
Voici un aperçu des concepts d’emprunt d’identité .NET.
Fondamentalement, vous utiliserez ces classes qui sont prêtes à l’emploi dans le framework .NET:
Le code peut souvent prendre beaucoup de temps et c’est pourquoi vous voyez de nombreux exemples comme celui que vous faites référence qui tentent de simplifier le processus.
“Emprunt d’identité” dans l’espace .NET signifie généralement l’exécution de code sous un compte d’utilisateur spécifique. Il s’agit d’un concept quelque peu distinct de l’access à ce compte utilisateur via un nom d’utilisateur et un mot de passe, bien que ces deux idées se combinent fréquemment. Je vais les décrire tous les deux, puis expliquer comment utiliser ma bibliothèque SimpleImpersonation , qui les utilise en interne.
Les API pour l’emprunt d’identité sont fournies dans .NET via l’espace de noms System.Security.Principal
:
Un code plus récent (.NET 4.6+, .NET Core, etc.) doit généralement utiliser WindowsIdentity.RunImpersonated
, qui accepte un handle vers le jeton du compte d’utilisateur, puis une Action
ou une fonction Func
pour le code à exécuter.
WindowsIdentity.RunImpersonated(tokenHandle, () => { // do whatever you want as this user. });
ou
var result = WindowsIdentity.RunImpersonated(tokenHandle, () => { // do whatever you want as this user. return result; });
Le code plus ancien utilisait la méthode WindowsIdentity.Impersonate
pour récupérer un object WindowsImpersonationContext
. Cet object implémente IDisposable
, donc devrait généralement être appelé depuis un bloc using
.
using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle)) { // do whatever you want as this user. }
Bien que cette API existe toujours dans .NET Framework, elle doit généralement être évitée et n’est pas disponible dans .NET Core ou .NET Standard.
L’API permettant d’utiliser un nom d’utilisateur et un mot de passe pour accéder à un compte d’utilisateur dans Windows est LogonUser
, qui est une API native Win32. Il n’y a pas actuellement d’API .NET intégrée pour l’appeler, il faut donc recourir à P / Invoke.
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool LogonUser(Ssortingng lpszUsername, Ssortingng lpszDomain, Ssortingng lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
C’est la définition de base de l’appel, mais il y a beaucoup plus à prendre en compte pour l’utiliser en production:
SecureSsortingng
lorsque vous pouvez en collecter en toute sécurité via les frappes d’utilisateur. La quantité de code à écrire pour illustrer tout cela est au-delà de ce que devrait contenir une réponse StackOverflow, IMHO.
Au lieu d’écrire tout cela vous-même, envisagez d’utiliser ma bibliothèque SimpleImpersonation , qui combine l’emprunt d’identité et l’access utilisateur dans une seule API. Il fonctionne bien dans les bases de code modernes et anciennes, avec la même API simple:
var credentials = new UserCredentials(domain, username, password); Impersonation.RunAsUser(credentials, logonType, () => { // do whatever you want as this user. });
ou
var credentials = new UserCredentials(domain, username, password); var result = Impersonation.RunAsUser(credentials, logonType, () => { // do whatever you want as this user. return something; });
Notez qu’il est très similaire à l’API WindowsIdentity.RunImpersonated
, mais ne nécessite pas que vous sachiez quelque chose sur les poignées de jeton.
Ceci est l’API à partir de la version 3.0.0. Voir le readme du projet pour plus de détails. Notez également qu’une version précédente de la bibliothèque utilisait une API avec le modèle IDisposable
, similaire à WindowsIdentity.Impersonate
. La nouvelle version est beaucoup plus sûre et les deux sont toujours utilisés en interne.
C’est probablement ce que vous voulez:
using System.Security.Principal; using(WindowsIdentity.GetCurrent().Impersonate()) { //your code goes here }
Mais j’ai vraiment besoin de plus de détails pour vous aider. Vous pouvez faire de l’emprunt d’identité avec un fichier de configuration (si vous essayez de le faire sur un site Web), ou via des décorateurs de méthode (atsortingbuts) si c’est un service WCF, ou via … vous avez l’idée.
De plus, si vous parlez d’emprunter l’identité d’un client qui a appelé un service particulier (ou une application Web), vous devez configurer le client correctement pour qu’il transmette les jetons appropriés.
Enfin, si vous voulez vraiment une délégation, vous devez également configurer correctement AD pour que les utilisateurs et les ordinateurs soient approuvés pour la délégation.
Modifier:
Jetez un oeil ici pour voir comment emprunter l’identité d’un utilisateur différent, et pour plus de documentation.
Voici mon port de vb.net de la réponse de Matt Johnson. J’ai ajouté un enum pour les types de connexion. LOGON32_LOGON_INTERACTIVE
était la première valeur enum qui fonctionnait pour le serveur SQL. Ma chaîne de connexion vient d’être approuvée. Aucun nom d’utilisateur / mot de passe dans la chaîne de connexion.
de
_ Public Class Impersonation Implements IDisposable Public Enum LogonTypes ''' ''' 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. ''' LOGON32_LOGON_INTERACTIVE = 2 '''''' This logon type is intended for high performance servers to authenticate plaintext passwords. ''' The LogonUser function does not cache credentials for this logon type. ''' LOGON32_LOGON_NETWORK = 3 '''''' 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. ''' LOGON32_LOGON_BATCH = 4 '''''' Indicates a service-type logon. The account provided must have the service privilege enabled. ''' LOGON32_LOGON_SERVICE = 5 '''''' 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. ''' LOGON32_LOGON_UNLOCK = 7 '''''' 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. ''' LOGON32_LOGON_NETWORK_CLEARTEXT = 8 '''''' 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. ''' LOGON32_LOGON_NEW_CREDENTIALS = 9 End Enum_ Private Shared Function LogonUser(lpszUsername As [Ssortingng], lpszDomain As [Ssortingng], lpszPassword As [Ssortingng], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean End Function Public Sub New(Domain As Ssortingng, UserName As Ssortingng, Password As Ssortingng, 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(Ssortingng.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 _ _ _ Private Shared Function CloseHandle(handle As IntPtr) As 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
_ Public Class Impersonation Implements IDisposable Public Enum LogonTypes ''' ''' 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. ''' LOGON32_LOGON_INTERACTIVE = 2 '''''' This logon type is intended for high performance servers to authenticate plaintext passwords. ''' The LogonUser function does not cache credentials for this logon type. ''' LOGON32_LOGON_NETWORK = 3 '''''' 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. ''' LOGON32_LOGON_BATCH = 4 '''''' Indicates a service-type logon. The account provided must have the service privilege enabled. ''' LOGON32_LOGON_SERVICE = 5 '''''' 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. ''' LOGON32_LOGON_UNLOCK = 7 '''''' 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. ''' LOGON32_LOGON_NETWORK_CLEARTEXT = 8 '''''' 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. ''' LOGON32_LOGON_NEW_CREDENTIALS = 9 End Enum_ Private Shared Function LogonUser(lpszUsername As [Ssortingng], lpszDomain As [Ssortingng], lpszPassword As [Ssortingng], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean End Function Public Sub New(Domain As Ssortingng, UserName As Ssortingng, Password As Ssortingng, 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(Ssortingng.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 _ _ _ Private Shared Function CloseHandle(handle As IntPtr) As 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
Vous devez utiliser une instruction Using
pour contenir du code à exécuter.
Voir plus de détail de ma réponse précédente J’ai créé un paquet Nuget Nuget
Code sur Github
échantillon: vous pouvez utiliser:
ssortingng login = ""; ssortingng domain = ""; ssortingng 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 le code complet:
using System; using System.Runtime.InteropServices; using System.Security.Principal; /// /// Object to change the user authticated /// public class UserImpersonation : IDisposable { /// /// Logon method (check athetification) from advapi32.dll /// /// /// /// /// /// /// /// [DllImport("advapi32.dll")] private static extern bool LogonUser(Ssortingng lpszUserName, Ssortingng lpszDomain, Ssortingng lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); /// /// Close /// /// /// [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool CloseHandle(IntPtr handle); private WindowsImpersonationContext _windowsImpersonationContext; private IntPtr _tokenHandle; private ssortingng _userName; private ssortingng _domain; private ssortingng _passWord; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; /// /// Initialize a UserImpersonation /// /// /// /// public UserImpersonation(ssortingng userName, ssortingng domain, ssortingng passWord) { _userName = userName; _domain = domain; _passWord = passWord; } /// /// Valiate the user inforamtion /// /// 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 /// /// Dispose the UserImpersonation connection /// public void Dispose() { if (_windowsImpersonationContext != null) _windowsImpersonationContext.Undo(); if (_tokenHandle != IntPtr.Zero) CloseHandle(_tokenHandle); } #endregion }
Je suis conscient que je suis en retard pour la fête, mais je considère que la bibliothèque de Phillip Allan-Harding est la meilleure pour ce cas et pour les autres.
Vous n’avez besoin que d’un petit morceau de code comme celui-ci:
private const ssortingng LOGIN = "mamy"; private const ssortingng DOMAIN = "mongo"; private const ssortingng PASSWORD = "HelloMongo2017"; private void DBConnection() { using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50)) { } }
Et ajoutez sa classe:
Emprunt d’identité .NET (C #) avec informations d’identification réseau
Mon exemple peut être utilisé si vous souhaitez que la connexion empruntée ait des informations d’identification réseau, mais qu’elle offre plus d’options.
Vous pouvez utiliser cette solution. (Utilisez le package nuget) Le code source est disponible sur: Github: https://github.com/michelcedric/UserImpersonation
Plus de détails https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/