Я пытаюсь запустить мое приложение winform с учетными данными пользователя локального окна, для этого я использую класс ниже для impersonation
,
public class Impersonation
{
/// <summary>
/// Impersonate given logon information.
/// </summary>
/// <param name="logon">Windows logon name.</param>
/// <param name="password">password</param>
/// <param name="domain">domain name</param>
/// <returns></returns>
public static bool Impersonate(string logon, string password, string domain)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (LogonUser(logon, 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 (null != impersonationContext) return true;
}
}
return false;
}
/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate()
{
impersonationContext.Undo();
}
[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 = CharSet.Auto, SetLastError = true)]
public extern static int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContext impersonationContext;
}
Теперь вот код для 'winform`код запуска,
static class Program
{
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string userName = Microsoft.VisualBasic.Interaction.InputBox("Enter User Name", "User Name");
string password = Microsoft.VisualBasic.Interaction.InputBox("Enter Password", "Password");
if (!Impersonation.Impersonate(userName, password, Environment.MachineName))
{
MessageBox.Show("Login failed.");
return;
}
Application.Run(new Form1());
Impersonation.UnImpersonate();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
}
}
Теперь, когда я передаю учетные данные для пользователя локального окна, вход в систему успешен, и при загрузке form
я получаю ошибку,
System.Security.SecurityException: 'Запрашиваемый доступ к реестру не разрешен.'
, а вот полная трассировка стека,
в System.ThrowHelper.ThrowSecurityException (ExceptionResourceресурс) в Microsoft.Win32.RegistryKey.OpenSubKey (имя строки, логическая запись) в Microsoft.Win32.RegistryKey.OpenSubKey (имя строки) в System.Windows.Forms.LinkUtilities.GetIEColor (имя строки) в System.Windows.Forms.LinkUtilities.get_IELinkColor () в System.Windows.Forms.LinkLabel.get_LinkColor () в System.Windows.Forms.LinkLabel.OnPaint (PaintEventArgs e) в System.Windows.Forms.Control.PaintWithErrorHandling (PaintEventArgs e, слой Int16) в System.Windows.Forms.Control.WmPaint (Message & m) в System.Windows.Forms.Control.WndProc (Message & m) в System.Windows.Forms.Label.WndProc (Message & m) в System.Windows.Forms.LinkLabel.WndProc (Сообщение & msg) в System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Сообщение & m) в System.Windows.Forms.Control.ControlNativeWindow.WndProc (Сообщение & m) в System.Windows.Forms.NativeWindow.DebuggableCallback (IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
В чем может быть причина?