". Net" Windows identity Impersonation (WindowsIdentity.Impersonate) When you read an Access database

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.