【.Net 学习系列】-- Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库
参考资料:
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数据库的更多相关文章
- 【.Net 学习系列】-- .Net 指定时间段内定时执行的Windows服务(System.Threading.Thread)
创建一个Windows服务项目:解决方案(右击)——> 添加 ——> 新建项目——>项目类型选择Windows——>模板选择Windows服务 ,如图: 编写Windows服务 ...
- Windows原理深入学习系列-Windows内核提权
这是[信安成长计划]的第 22 篇文章 0x00 目录 0x01 介绍 0x02 替换 Token 0x03 编辑 ACL 0x04 修改 Privileges 0x05 参考文章 继续纠正网上文章中 ...
- Html5 学习系列(六)Html5本地存储和本地数据库
一个网站如何能在客户的浏览器存储更多的数据呢? 在Html4的时代在浏览器端存储点网站个性化的数据,尤其是用户浏览器的痕迹,用户的相关数据等一般只能存储在Cookie中,但是大多是浏览器对于Cooki ...
- Django学习系列15:把POST请求中的数据存入数据库
要修改针对首页中的POST请求的测试.希望视图把新添加的待办事项存入数据库,而不是直接传给响应. 为了测试这个操作,要在现有的测试方法test_can_save_a_post_request中添加3行 ...
- thinkphp学习简易教程(二) thinkphp连接读取MySQL数据库
首先, 在本地服务器中新建项目APP,依据第一讲中的步骤配置好thinkphp,这里为了测试方便,不分前台和后台模块,统一把模块路径设为'./APP/'. 1.新建数据库myapp,以及数据库表thi ...
- OAF_文件系列9_实现OAF解析Excel并读取至数据库JXL
ddd puroder. webui. poLineExcelImport.java
- Windows 服务多语言化时读取配置文件失败的问题。
在Installer中,按一般读取配置文件的方法(ConfigurationManager.AppSettings["CultureName"])读取不到内容. 可以这样读取: v ...
- 转:细说ASP.NET Windows身份认证
转自:https://www.cnblogs.com/fish-li/archive/2012/05/07/2486840.html 细说ASP.NET Windows身份认证 阅读目录 开始 认识A ...
- 细说ASP.NET Windows身份认证
上篇博客我谈到了一些关于ASP.NET Forms身份认证方面的话题,这次的博客将主要介绍ASP.NET Windows身份认证. Forms身份认证虽然使用广泛,不过,如果是在 Windows Ac ...
随机推荐
- 微信小程序开发系列五:微信小程序中如何响应用户输入事件
微信小程序开发系列教程 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 微信小程序开发系列二:微信小程序的视图设计 微信小程序开发系列三:微信小程序的调试方法 微信小程序开发系列四:微信小程序 ...
- 数组排序 sort
数组排序 this.dataShow = this.data.sort((a, b) => { return parseInt(a[this.innerOrderBy]) - parseInt( ...
- this.treeData = JSON.parse(JSON.stringify(this.d)) 树的序列化反序列化
this.treeData = JSON.parse(JSON.stringify(this.d))
- Python基础2 列表 元祖 字符串 字典 集合 文件操作 -DAY2
本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...
- ROI(Region of Interesting)
ROI(region of interest),感兴趣区域.机器视觉.图像处理中,从被处理的图像以方框.圆.椭圆.不规则多边形等方式勾勒出需要处理的区域,称为感兴趣区域,ROI.在Halcon.Ope ...
- PHP08 数组和数据结构
学习要点 数组的分类 数组的定义 数组的遍历 预定义数组 数组的相关处理函数 PHP操作数组需要注意的细节 数组的分类 关于PHP数组 由于PHP是弱类型的编程语言,所以PHP数组中的数组变量可以存储 ...
- dpdk快速编译使用
QuickStart 环境 dpdk: dpdk-17.11 运行前配置 配置系统HugePages #mkdir /mnt/huge_1GB/ #vim /etc/fstab nodev /mnt/ ...
- 2019天梯赛练习题(L1专项练习)
7-1 水仙花数 (20 分) 水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身.例如:1. 本题要求编写程序,计算所有N位水仙花数. 输入样例: 3 输出样例: 153 ...
- 文本三剑客之grep
接受正则表达式,按行匹配,将会过滤出匹配的所有行 格式: grep [OPTION]... PATTERN [FILE]... 可以看出,grep后可以同时接多个文件 选项OPTIO ...
- mysql多字段组合删除重复行
DELETEFROM boll_paramWHERE id in ( SELECT a.id FROM ( SELECT id FROM boll_param WHERE (symbol, time_ ...