在模拟管理员用户将 .cer(证书文件)文件安装到 LocalComputer 时遇到问题...正在为 CurrentUser 工作完美安装。
我总是收到错误消息“拒绝访问”。
使用以下代码进行模拟:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class ImpersonatedUser : IDisposable
{
IntPtr userHandle;
WindowsImpersonationContext impersonationContext;
public ImpersonatedUser(string domain,string user, string password)
{
userHandle = IntPtr.Zero;
bool loggedOn = LogonUser(
user,
domain,
password,
LogonType.Interactive,
LogonProvider.Default,
out userHandle);
if (!loggedOn)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
}
public void Dispose()
{
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
userHandle = IntPtr.Zero;
impersonationContext.Undo();
}
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
LogonType dwLogonType,
LogonProvider dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
enum LogonType : int
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
NetworkCleartext = 8,
NewCredentials = 9,
}
enum LogonProvider : int
{
Default = 0,
WINNT50 = 3,
}
这是证书安装方法:
private static void InstallCertificate(string cerFileName, StoreName storeName)
{
LoginInfo loginInfo = new LoginInfo();
X509Certificate2 certificate = new X509Certificate2(cerFileName);
X509Store store = new X509Store(storeName, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();
}
catch (Exception e)
{
string CertName = Path.GetFileName(cerFileName);
string source = e.Source.ToString();
string message = e.Message.ToString();
string messagetext = string.Format("Certificate installation \"{0}\" was not succsessfull Error: {1}", CertName, message);
StringBuilder messagestring = new StringBuilder();
messagestring.Append(source);
messagestring.Append(message);
MessageBox.Show(messagetext, "Install Certificate Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
这就是我在 ImpersonatedUser 中调用方法的方式。
using (new ImpersonatedUser(loginInfo.DomainName, loginInfo.UserName, loginInfo.Password))
{
MessageBox.Show(WindowsIdentity.GetCurrent().Name);
InstallCertificate(certpath, StoreName.TrustedPublisher);
}