c# - 安装证书时模拟用户

标签 c#

模拟管理员用户将 .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);

                }

最佳答案

MS 有一个很好的帮助页面,示例位于:http://msdn.microsoft.com/en-us/library/w070t6ka.aspx

您的代码之间的明显区别是您没有在函数中包含 [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] 限定符。如果这是图书馆的一部分,您也需要对整个图书馆这样做。

我假设您登录的用户有权安装证书——请确保您的用户拥有这些权限。

关于c# - 安装证书时模拟用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18961109/

相关文章:

c# - 如何开始用 C# 开发 Sphero-Ball Windows 应用程序?

c# - Microsoft Outlook 发送和电子邮件自动化 C#

C#:如何在 form.cs 中引用 Program.cs 中的内容?

c# - .NET 实例化错误

c# - 如何使用 EF5 和存储库检查给定 ID 的记录是否已存在

c# - Open-XML 保存 word 文档产生损坏的文件

C# 显示表格中的某些行

C# 和 Excel 文件

c# - 我如何在开发时调试 nopCommerce 插件?

c# - Access 更新语句在 C# 中不起作用