一早在浏览代码时看到如下代码(我想这段代码的来源是kb306158),这段代码的作用是,当一个通过Active Directory账号登陆系统的用户,需要上传、创建目录、下载时,需要先校验该用户是否具有目录操作权限, 代码如下:

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
private string _logOnUsername;
private string _logOnDomain;
private string _logOnPassword;WindowsImpersonationContext impersonationContext;// to check whether the acct info input is a logoned one,
// if past the validation, output a token
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int LogonUser(String lpszUserName,String lpszDomain,String lpszPassword,int dwLogonType,int dwLogonProvider,ref IntPtr phToken);// create a new token derived from the input token
[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto,SetLastError = true)]
public extern static int DuplicateToken(IntPtr hToken,int impersonationLevel,ref IntPtr hNewToken);// to impersonate
private bool impersonateValidUser(String userName, String domain, String password)
{WindowsIdentity tempWindowsIdentity;IntPtr token = IntPtr.Zero;IntPtr tokenDuplicate = IntPtr.Zero;// validate whether logoned on with the supplied parametersif (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT, ref token) != 0){// SecurityImpersonation// The server can impersonate the client's security context on the local system.if (DuplicateToken(token, 2, ref tokenDuplicate) != 0){tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);impersonationContext = tempWindowsIdentity.Impersonate();if (impersonationContext != null)return true;elsereturn false;}elsereturn false;}elsereturn false;
}private void undoImpersonation()
{impersonationContext.Undo();
}// the parameters' value are all kept in web.config,
// it's a fixed account, not current logined user's acct.
public FileAccess(string logonDomain, string logonUsername, string logonPassword)
{_logOnDomain = logonDomain;_logOnUsername = logonUsername;_logOnPassword = logonPassword;
}public bool FileExists(string filePathName)
{if (impersonateValidUser(_logOnUsername, _logOnDomain, _logOnPassword)){try{if (File.Exists(filePathName)){return true;}else{return false;}}finally{undoImpersonation();}}else{throw (new Exception("Failed in impersonation."));}
}

代码中使用FileAccess进行对象初始化,其中logonDomain,logonUserName,logonPWD均被配置于web.config中。使用impersonateValidUser方法校验目录操作权限,

Q: 为什么需要DuplicateToken

A: 先要了解进行Windows校验所需要的一点基础,文中认为使用LogonUser后拿到的token是当前用户的,我们不能用它来创建对象或是做别的什么事,这样不安全,所以应该使用如下两种中的一种来创建被复制的新token,

> SecurityImpersonation    The server can impersonate the client's security context on the local system.

> SecurityDelegation    The server can impersonate the client's security context on remote systems.

At the SecurityImpersonation level, most of the thread's actions occur in the security context of the thread's impersonation token rather than in the primary token of the process that owns the thread. For example, if an impersonating thread opens a securable object, the system uses the impersonation token to check the thread's access. Similarly, if an impersonating thread creates a new object, for example by calling the CreateFile function, the owner of the new object is the default owner from the client's access token.

Q: 这个被模拟的用户(即此处的FileAccess中传入的帐号信息)的权限应该设置为什么?

A: 在KB306158中,已经给出如下解决方案

> 为 ASPNET 帐户授予“作为操作系统的一部分”权限。(注意:我们不建议使用这种方法解决此问题。)

> 在 Machine.config 文件的 <processModel> 配置节中,将运行 Aspnet_wp.exe 进程所使用的帐户更改为 System 帐户。

在此贴中,这位大牛提出了这个问题,他认为无论是使用LogonUser还是使用System.DiretoryServices都是不完美的,有漏洞的。比如LogonUser必须会提供一个有SE_CHANGE_NOTIFY_NAME权限的账号,这个比较麻烦,使用DirectoryServices则需要查看AD属性,并认为这种方式会在客户端留下AD scheme的缓存,代价太大不划算,且GetLastError捕捉的异常也并不能100%定位是否是用户校验未通过,见下面这段代码。

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{// validate the credentialsbool isValid = pc.ValidateCredentials("myuser", "mypassword")
}

还可以进行一些延伸阅读 See also:

  1. Create a Web Service Method to Manage a NT Service
  2. 微软KB306158:How to implement impersonation in an ASP.NET application (可自行将en-us改成zh-cn转向中文版)
  3. 关于etern关键字和DLLImport
  4. DuplicateToken Function
  5. WindowsIdentity
  6. impersonationContext.Undo()
  7. WindowsIdentity.Impersonate Method ()

我觉得到了这一步,我已经对windows/AD登陆用户的校验大致有了一点了解。

转载于:https://www.cnblogs.com/syveen/archive/2011/03/06/1972265.html

使用C# impersonation进行windows帐号的校验相关推荐

  1. Windows 帐号管理相关操作

    1.  增加\删除 user到指定的group 右击"我的电脑"--> 管理 --> System Tools --> Local User and Groups ...

  2. 关于 web.config impersonate 帐号模拟

    1.模拟 IIS 验证的帐户或用户 若要在收到 ASP.NET 应用程序中每个页的每个请求时模拟 Microsoft Internet 信息服务 (IIS) 身份验证用户,必须在此应用程序的 Web. ...

  3. [翻译]当SA帐号丢失时怎么办

    Q:我遇到了一个灾难:我丢失了SQL Server 2005的SA密码,有办法恢复么?我遵循了最佳安全实践,从sysadmin中删除了builtin\Administrators帐号,现在没其他人是s ...

  4. 【QT 数据库专辑】【04】WIN7下搭建本地SQL SERVER数据库 - 手把手-登录远程数据库帐号设定问题

    前言: 多次数据库试验经验报名,远程数据库的访问问题,大多数是因为有帐号和访问权限的原因. 本文,通过从安装SQL SERVER开始暂时,我们在远程访问SQL SERVER数据库的时候可能遇到的问题. ...

  5. vivo 帐号服务稳定性建设之路

    作者:vivo 互联网平台产品研发团队- Shi Jianhua.Sun Song 帐号是一个核心的基础服务,对于基础服务而言稳定性就是生命线.在这篇文章中,将与大家分享我们在帐号稳定性建设方面的经验 ...

  6. vivo 帐号服务稳定性建设之路-平台产品系列06

    作者:vivo 互联网平台产品研发团队- Shi Jianhua.Sun Song 帐号是一个核心的基础服务,对于基础服务而言稳定性就是生命线.在这篇文章中,将与大家分享我们在帐号稳定性建设方面的经验 ...

  7. windows phone 越狱教程:利用学生帐号解锁并部署软件教程(图文并茂)

    之前老是看到有学生帐号可以越狱,但一直以来都觉得比较复杂,不想下手. 近日,TX微信出来了,很多人都想装,可是装不了, 所以下决心研究一下学生帐号越狱. 网上看教程,发现很多都是不全面,有些只有一半, ...

  8. linux+添加git+ssh+keys,为github帐号添加SSH keys(Linux和Windows)(示例代码)

    一.Linux增加ssh keys方法: 使用git clone命令从github上同步github上的代码库时,如果使用SSH链接(如我自己的cofface_recovery项目:[email pr ...

  9. ndows live id怎么登陆,手机如何注册和使用Windows Live ID帐号

    首先您可以在百度搜索Windows Live账号注册即可找到入口开始注册了. Windows Live 与 Windows Phone Windows Phone是最新一代的从设计开始即与Window ...

最新文章

  1. 嵌入式http服务器boa 简介
  2. websocket 连接本地端口_聊聊 WebSocket,还有 HTTP
  3. leetcode 309. Best Time to Buy and Sell Stock with Cooldown | 309. 最佳买卖股票时机含冷冻期(动态规划)
  4. Linux—系统启动类故障之 GRUB引导故障
  5. 魔力转圈圈(快速幂)
  6. 菜式介绍:风味黄泥烤鸡
  7. nyoj 最强DE 战斗力 (数论入门)
  8. 今天来黑一黑Intel的傲腾
  9. 传感器实验——光敏电阻传感器
  10. 常用网络端口用处归纳
  11. 泛函分析 01.02 距离空间-基本概念
  12. Win11 PE下如何快速设置IP如何新建共享文件夹并设置为everyone完全控制权限
  13. 【问题记录】02 Linux服务器安装MySql数据库报错:Failing package is: mysql-community-server GPG Keys are configured as
  14. 如何用Python挖掘“啤酒和尿布”的关系?(Apriori算法挖掘关联规则)
  15. Git分支管理及命名规范
  16. Unity导出视频/截图
  17. 用Javascript实现关闭广告案例
  18. 测试使用CSDN写博客
  19. 一个简单的pingpong程序测试mpi消息通讯的开销及并行计算通讯启动时间测算
  20. delphi三层中间件 框架【首页】

热门文章

  1. Iterator pattern-迭代器模式
  2. 25.4. Phing
  3. CentOS7安装Nagios
  4. 系统的本地策略不允许您采用交互式登录
  5. oracle关键字 bulk,oracle和sqlserver的一些保留关键字
  6. python 颜色空间转换_python opencv入门 颜色空间转换(9)
  7. atom上网本 安装linux,拆东墙补西墙?多数Atom上网本或将无法安装Windows 7
  8. MATLAB solve函数计算得到lambertw函数,用vpa转换即可
  9. 计算机小键盘价格,带小键盘的笔记本电脑是多少寸
  10. c语言void和null,C语言:为什么我得到NULL?