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

时间:2022-06-28 00:04:53

参考资料:

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 = ;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = ; // 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”中当前登录的用户文件夹上设置要模拟用户的的访问权限