【.Net】Windows身份類比(WindowsIdentity.Impersonate)時讀取Access資料庫

來源:互聯網
上載者:User

標籤: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資料庫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.