码迷,mamicode.com
首页 > 数据库 > 详细

【.Net】Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库

时间:2017-07-21 18:55:16      阅读:392      评论:0      收藏:0      [点我收藏+]

标签:unicode   safe   ice   ntp   sel   ror   dbconnect   public   use   

参考资料:

 WindowsIdentity.Impersonate https://msdn.microsoft.com/zh-cn/library/w070t6ka(v=vs.110).aspx

 Acess数据库读取 https://msdn.microsoft.com/zh-cn/library/system.data.oledb.oledbdatareader(v=vs.80).aspx

 

代码实现:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Data.OleDb;

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, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    // 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)
    {
        SafeTokenHandle safeTokenHandle;
        try
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser("username", ".", "password", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                // Check the identity.
                Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);
                // Use the token handle returned by LogonUser.
                using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {

                        // Check the identity.
                        Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);

                        using (OleDbConnection conn = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = D:\DamonFile\agms60\AgmsGZ.mdb"))
                        //using (OleDbConnection conn = new OleDbConnection(@"Provider =Microsoft.Jet.OLEDB.4.0;Data Source=D:\DamonFile\agms60\AgmsGZ.mdb"))
                        {
                            conn.Open();
                            OleDbCommand cmd = conn.CreateCommand();
                            cmd.CommandText = "SELECT top 10 User_name FROM Operate_log";
                            cmd.CommandType = System.Data.CommandType.Text;
                            OleDbDataReader reader = cmd.ExecuteReader();
                            while (reader.Read())
                            {
                                Console.WriteLine(reader["User_name"].ToString());
                            }
                        }


                    }
                }
                // Releasing the context object stops the impersonation
                // Check the identity.
                Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);

            }

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }
        Console.ReadLine();

    }
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}

 注意:

如果在访问Access数据库出现“未指定的错误”时,请在“C:\Users”中当前登录的用户文件夹上设置要模拟用户的的访问权限

 

【.Net】Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库

标签:unicode   safe   ice   ntp   sel   ror   dbconnect   public   use   

原文地址:http://www.cnblogs.com/elliot-lei/p/7219103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!