ASP.NET: impersonare un dominio su VMWare
-
07-07-2019 - |
Domanda
Devo impersonarmi come utente di dominio in un'applicazione ASP.NET in esecuzione su una macchina VMWare. Poiché la macchina VMWare non si trova nel dominio, ASP.NET non è in grado di risolvere il token utente (specificato in web.config). C'è un modo per farlo?
Grazie in anticipo, Petr
Soluzione
Uso questa classe che ho sempre scritto e funziona come un incantesimo!
using System;
using System.Security.Principal;
/// <summary>
/// Changes the security context the application runs under.
/// </summary>
public class ImpersonateHelper : IDisposable
{
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
private IntPtr _token = IntPtr.Zero;
private WindowsImpersonationContext _impersonatedUser = null;
public IntPtr Token
{
get { return _token; }
set { _token = value; }
}
public ImpersonateHelper(IntPtr token)
{
_token = token;
}
/// <summary>
/// Switch the user to that set by the Token property
/// </summary>
public void Impersonate()
{
if (_token == IntPtr.Zero)
_token = WindowsIdentity.GetCurrent().Token;
_impersonatedUser = WindowsIdentity.Impersonate(_token);
}
/// <summary>
/// Revert to the identity (user) before Impersonate() was called
/// </summary>
public void Undo()
{
if (_impersonatedUser != null)
_impersonatedUser.Undo();
}
#region IDisposable Members
private bool _isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
if (_impersonatedUser != null)
_impersonatedUser.Dispose();
}
CloseHandle(_token);
_token = IntPtr.Zero;
}
_isDisposed = true;
}
~ImpersonateHelper()
{
Dispose(false);
}
#endregion
}
Quindi lo chiami dalla classe client come:
//Run task as the impersonated user and not as NETWORKSERVICE or ASPNET (in IIS5)
try{
impersonate.Impersonate();
//Do work that needs to run as domain user here...
}
finally
{
//Revert impersonation to NETWORKSERVICE or ASPNET
if (impersonate != null)
{
impersonate.Undo();
impersonate.Dispose();
}
}
Buona fortuna!
Altri suggerimenti
Questa potrebbe essere la stupida risposta ovvia, ma potresti aggiungere la tua macchina VMWare al dominio.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow