Resources:
windowsidentity.impersonate Https://msdn.microsoft.com/zh-cn/library/w070t6ka (v=vs.110). aspx
acess Database Read https://msdn.microsoft.com/zh-cn/library/system.data.oledb.oledbdatareader (v=vs.80). aspx
Code implementation:
usingSystem;usingSystem.Runtime.InteropServices;usingSystem.Security.Principal;usingSystem.Security.Permissions;usingMicrosoft.Win32.SafeHandles;usingSystem.Runtime.ConstrainedExecution;usingsystem.security;usingSystem.Data.OleDb; Public classimpersonationdemo{[DllImport ("Advapi32.dll", SetLastError =true, CharSet =CharSet.Unicode)] Public Static extern BOOLLogonUser (String lpszUserName, String lpszdomain, String lpszpassword,intdwLogonType,intdwLogonProvider, outsafetokenhandle Phtoken); [DllImport ("Kernel32.dll", CharSet =CharSet.Auto)] Public extern Static BOOLCloseHandle (IntPtr handle); //Test Harness. //If You incorporate the this code into a DLL, being sure to demand FullTrust.[PermissionSetAttribute (SecurityAction.Demand, Name ="FullTrust")] Public Static voidMain (string[] args) {Safetokenhandle safetokenhandle; Try { Const intLogon32_provider_default =0; //This parameter causes LogonUser to create a primary token. Const intLogon32_logon_interactive =2; //Call LogonUser to obtain a handle to an access token. BOOLreturnvalue = LogonUser ("username",".","Password", Logon32_logon_interactive, Logon32_provider_default, outsafetokenhandle); if(false==returnvalue) { intRET =Marshal.GetLastWin32Error (); Console.WriteLine ("LogonUser failed with error code: {0}", ret); Throw NewSystem.ComponentModel.Win32Exception (ret); } using(Safetokenhandle) {Console.WriteLine ("did LogonUser succeed?"+ (returnvalue?)"Yes":"No")); Console.WriteLine ("Value of Windows NT tokens:"+safetokenhandle); //Check the identity.Console.WriteLine ("Before impersonation:"+windowsidentity.getcurrent (). Name); //Use the token handle returned by LogonUser. using(WindowsIdentity newId =NewWindowsIdentity (Safetokenhandle.dangerousgethandle ())) { using(WindowsImpersonationContext Impersonateduser =newid.impersonate ()) { //Check the identity.Console.WriteLine ("After impersonation:"+windowsidentity.getcurrent (). Name); using(OleDbConnection conn =NewOleDbConnection (@"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 ten 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 classsafetokenhandle:safehandlezeroorminusoneisinvalid{Privatesafetokenhandle ():Base(true) {} [DllImport ("Kernel32.dll"] [ReliabilityContract (Consistency.willnotcorruptstate, cer.success)] [suppressunmanagedcodesecurity] [return: MarshalAs (unmanagedtype.bool)]Private Static extern BOOLCloseHandle (IntPtr handle); protected Override BOOLReleaseHandle () {returnCloseHandle (handle); }}
Note:
If you are accessing an Access database with unspecified errors, set the access permissions on the user folder that you are currently logged on in C:\Users to impersonate the user
". Net" Windows identity Impersonation (WindowsIdentity.Impersonate) When you read an Access database