参考资料:

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. 详解nginx.conf文件配置项(包括负载均衡)

    http://www.cnblogs.com/hsapphire/archive/2010/04/08/1707109.html #运行用户 user  nobody nobody; #启动进程 wo ...

  2. Eclipse被卡死了或者失去响应了后分析根源的一个小技巧

    提升程序员工作效率的工具/技巧推荐系列 推荐一个功能强大的文件搜索工具SearchMyFiles 介绍一个好用的免费流程图和UML绘制软件-Diagram Designer 介绍Windows任务管理 ...

  3. dockerfile 的最佳实践

    Dockerfile 编写nginx容器 [root@mast nginx]# cat Dockerfile FROM centos MAINTAINER zhaoruidong RUN yum -y ...

  4. java根据freeMark模板生成内容

    根据ftl模板生成文件内容可以用来生成代码模板,如下所示: aa.ftl name : ${name} age : ${age} aa.java package mall_tools; import ...

  5. luogu 1968 美元汇率

    https://www.luogu.org/problemnew/show/P1968 定义二维数组f[ ][ ],f[i][1]表示在第i天将马克变为美元,f[i][2]表示在第i天将美元变为马克. ...

  6. Linux中vim编辑器常用命令

    移动光标 Ctrl+f:屏幕向下移动一页,相当于[Page Down]按键Ctrl+b:屏幕向上移动一页,相当与[PageUp]按键 0或功能键[Home]:数字‘0’:移动到这一行的最前面的字符处$ ...

  7. memcached内存分配

    Memcached默认情况下采用了名为Slab Allocator的机制分配.管理内存,最大单个存储对象大小为1M. page:分配给slab的最小内存空间,默认为1M,可以在启动时通过-l参数修改 ...

  8. jQuery的on绑定click和直接绑定click区别

    状况之外 在之前的公司并没有遇到这个问题,也就没有深究.直到自己换了现在的公司,刚来第二天就开始写别人写到一半的项目,很无奈,不是原生就是jquery,由于项目急,已经来不及切换框架重新布局,只能继续 ...

  9. C语言学习12

    希尔排序 //希尔排序 #include <stdio.h> void main() { ], i; int shell(int a[], int n); printf("请输入 ...

  10. 【HDU 2028】Lowest Common Multiple Plus

    Problem Description 求n个数的最小公倍数. Input 输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数. Output 为每组测试数据输出它们的最小公倍数 ...