我用C#編寫了一個簡單的Windows窗體程序。我希望能夠輸入一個Windows用戶名和密碼,並且當我點擊一個登錄按鈕來運行代碼作爲用戶輸入的輸入。更改用戶運行Windows窗體程序
3
A
回答
4
你可以使用WindowsIdentity.Impersonate方法來達到這個目的, 。此方法允許代碼模擬不同的Windows用戶。這裏是一個很好的樣本對這個方法的鏈接瞭解更多信息:
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx
完整的示例:
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample can be run only on Windows XP. The default Windows 2000 security policy
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk.
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment. To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Windows.Forms;
[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
[DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
try
{
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
Console.Write("Enter the name of the domain on which to log on: ");
domainName = Console.ReadLine();
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
userName = Console.ReadLine();
Console.Write("Enter the password for {0}: ", userName);
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + tokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Stop impersonating the user.
impersonatedUser.Undo();
// Check the identity.
Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
catch(Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}
2
模仿會改變線程上下文。如果您想更改身份並啓動單獨的進程,則必須使用runas命令。
由Keith Brown編寫的Windows安全.NET開發人員指南是一本很好的閱讀,它描述了所有的安全場景。 Online version也可用。
相關問題
- 1. Windows窗體:在運行時更改應用程序主窗口
- 2. 更新Windows窗體應用程序以在Windows 8.1上運行
- 3. Delphi在應用程序運行時更改主窗體
- 4. 在運行時更改窗體窗體應用程序(exe)圖標
- 5. 運行Windows窗體應用程序從Windows服務
- 6. Windows窗體應用程序在Windows託管服務上運行
- 7. 動態更改Windows窗體窗口標題(運行時)
- 8. 如何使Windows窗體應用程序以不同的用戶身份運行?
- 9. Windows窗體應用程序
- 10. 如何更改Windows窗體應用程序的標題圖標
- 11. 更改主題後Windows窗體應用程序退出
- 12. 更改Windows窗體應用程序的標題
- 13. 從Windows窗體更改爲WPF應用程序
- 14. 更改Windows窗體應用程序中的默認圖標
- 15. Windows窗體:登錄後創建主應用程序,運行哪個窗體?
- 16. 如何在C#應用程序中運行Windows窗體
- 17. 在Linux上運行Windows窗體應用程序
- 18. 從asp.net頁面運行windows窗體應用程序
- 19. 如何正確編譯和運行Windows窗體應用程序
- 20. C#從服務(和Vista中)運行Windows窗體應用程序
- 21. 從Windows窗體運行WPF應用程序
- 22. 在Windows窗體中運行另一個應用程序
- 23. 從Windows窗體運行控制檯應用程序
- 24. 運行Windows窗體應用程序。從服務
- 25. 無法在其他PC上運行Windows窗體應用程序
- 26. 如何在Windows窗體應用程序中運行PowerShell命令?
- 27. C#/ Windows窗體:應用程序運行但無響應
- 28. 運行或窗體應用程序
- 29. 在Windows窗體中更改語言運行時
- 30. 在Windows窗體運行時更改ASMX服務的地址
可以在沒有win32 API調用的情況下完成嗎? – chakrit 2008-09-07 17:27:26