参考资料:

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”中当前登录的用户文件夹上设置要模拟用户的的访问权限

【.Net 学习系列】-- Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库的更多相关文章

  1. 【.Net 学习系列】-- .Net 指定时间段内定时执行的Windows服务(System.Threading.Thread)

    创建一个Windows服务项目:解决方案(右击)——> 添加 ——> 新建项目——>项目类型选择Windows——>模板选择Windows服务 ,如图: 编写Windows服务 ...

  2. Windows原理深入学习系列-Windows内核提权

    这是[信安成长计划]的第 22 篇文章 0x00 目录 0x01 介绍 0x02 替换 Token 0x03 编辑 ACL 0x04 修改 Privileges 0x05 参考文章 继续纠正网上文章中 ...

  3. Html5 学习系列(六)Html5本地存储和本地数据库

    一个网站如何能在客户的浏览器存储更多的数据呢? 在Html4的时代在浏览器端存储点网站个性化的数据,尤其是用户浏览器的痕迹,用户的相关数据等一般只能存储在Cookie中,但是大多是浏览器对于Cooki ...

  4. Django学习系列15:把POST请求中的数据存入数据库

    要修改针对首页中的POST请求的测试.希望视图把新添加的待办事项存入数据库,而不是直接传给响应. 为了测试这个操作,要在现有的测试方法test_can_save_a_post_request中添加3行 ...

  5. thinkphp学习简易教程(二) thinkphp连接读取MySQL数据库

    首先, 在本地服务器中新建项目APP,依据第一讲中的步骤配置好thinkphp,这里为了测试方便,不分前台和后台模块,统一把模块路径设为'./APP/'. 1.新建数据库myapp,以及数据库表thi ...

  6. OAF_文件系列9_实现OAF解析Excel并读取至数据库JXL

    ddd puroder. webui. poLineExcelImport.java

  7. Windows 服务多语言化时读取配置文件失败的问题。

    在Installer中,按一般读取配置文件的方法(ConfigurationManager.AppSettings["CultureName"])读取不到内容. 可以这样读取: v ...

  8. 转:细说ASP.NET Windows身份认证

    转自:https://www.cnblogs.com/fish-li/archive/2012/05/07/2486840.html 细说ASP.NET Windows身份认证 阅读目录 开始 认识A ...

  9. 细说ASP.NET Windows身份认证

    上篇博客我谈到了一些关于ASP.NET Forms身份认证方面的话题,这次的博客将主要介绍ASP.NET Windows身份认证. Forms身份认证虽然使用广泛,不过,如果是在 Windows Ac ...

随机推荐

  1. Windows下使用python库 curses遇到错误消息的解决方案

    在Windows系统下执行python应用时,有时会遇到错误信息: ModuleNotFoundError: No module named '_curses'. 然而查看Windows系统里pyth ...

  2. Oracle的Central Inventory和Local inventory详解

    很多朋友对Oracle的inventory信息不太了解以至遇到相关的问题不知道如何处理,这篇文章我们将详细讲解Oracle的Central Inventory (oraInventory)和Local ...

  3. mysql 中modify和change区别(以及使用modify修改字段名称报错)

    使用modify修改字段报错如下: mysql> alter table student modify name sname char(16);ERROR 1064 (42000): You h ...

  4. 产生多种anchor的代码讲解!很好!

    http://blog.csdn.net/xzzppp/article/details/52317863 源代码:https://github.com/rbgirshick/py-faster-rcn ...

  5. postman使用--环境变量

    变量 postman提供了变量设置,有四种变量类型本地变量全局变量环境变量 数据变量 什么是环境变量 环境变量指在不同环境,同一个变量值随着环境不同而变化,比如在测试环境时,host为:dev.pos ...

  6. 牛客OI赛制测试赛2 A 无序组数

    链接:https://www.nowcoder.com/acm/contest/185/A来源:牛客网 题目描述 给出一个二元组(A,B) 求出无序二元组(a,b) 使得(a|A,b|B)的组数 无序 ...

  7. tornado框架基础03-请求与响应

    01 请求与响应 请求 浏览器在发送请求的时候,会发送具体的请求信息,由请求行,请求消息头,请求正文 请求消息头 向服务器传递附加信息 Accept: 浏览器可以接受的MIME类型. Accept-C ...

  8. 开发语言之---Python

    Python,如果你想进军AI,或是不想被自动化运维淘汰,Python是一门必须课. 在未来的大学课堂上,也许也会将Python加入必修中,就像Java一样. Python之“Hello World” ...

  9. POJ 1985 Cow Marathon (求树的直径)

    Description After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to ge ...

  10. UVALive - 6275 Joint Venture (二分)

    题意: 给定一个整数w, 然后给定n个数, 问有没有两个数之和恰好为w 分析: 现将n个数数组a[]排序, 然后用两个变量i,j指向开头和末尾, 如果a[i] + a[j] > w, i++, ...