// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// On Windows Vista and later this sample must be run as an administrator. 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; 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
{
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
Console.Write("Enter the name of the domain on which to log on: ");
domainName = Console.ReadLine(); Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
userName = Console.ReadLine(); Console.Write("Enter the password for {0}: ", userName); 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, domainName, Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle); Console.WriteLine("LogonUser called."); 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);
}
}
// 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);
}
finally
{
Console.ReadKey();
}
}
} 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);
}
}

impersonate a user的更多相关文章

  1. How to Programmatically Impersonate Users in SharePoint

      Sometimes when creating SharePoint web or console applications, you may need to execute specific c ...

  2. <!--转换office时需要此配置 --> <identity impersonate="true" />

    1.需要对Office 进行操作时 ,添加权限  <!--转换office时需要此配置 --> <identity impersonate="true" /> ...

  3. Ambari安装HDP问题:User root is not allowed to impersonate anonymous.User: hcat is not allowed to impersonate ambari-qa

    User root is not allowed to impersonate anonymous 修改hadoop 配置文件 etc/hadoop/core-site.xml,加入如下配置项 < ...

  4. Hive JDBC:java.lang.RuntimeException: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.authorize.AuthorizationException): User: root is not allowed to impersonate anonymous

    今天使用JDBC来操作Hive时,首先启动了hive远程服务模式:hiveserver2 &(表示后台运行),然后到eclipse中运行程序时出现错误: java.sql.SQLExcepti ...

  5. User root is not allowed to impersonate anonymous

    User root is not allowed to impersonate anonymous ava.lang.RuntimeException: org.apache.hadoop.ipc.R ...

  6. 【原创】大叔经验分享(38)beeline连接hiveserver2报错impersonate

    beeline连接hiveserver2报错 Error: Could not open client transport with JDBC Uri: jdbc:hive2://localhost: ...

  7. hiveserver2连接报错: User: root is not allowed to impersonate anonymous (state=08S01,code=0)

    使用HiveServer2运行时,启动好HiveServer后运行 private static String url = "jdbc:hive2://192.168.213.132:100 ...

  8. 如果应用程序正在通过 <identity impersonate="true"/> 模拟,则标识将为匿名用户(通常为 IUSR_MACHINENAME)或经过身份验证的请求用户。

    在配置文件中添加 <identity   impersonate= "true "   userName= "Administrator "   pass ...

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

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

随机推荐

  1. Hungary(匈牙利算法)——二分图最大匹配

    在复习匈牙利算法的时候,发现这么一篇介绍匈牙利算法的文章,非常通俗易懂,所以就借鉴过来了. 复杂度:邻接矩阵:O(v^3)邻接表:O(V*E) 附上链接:趣写算法系列之--匈牙利算法 下面就附上代码吧 ...

  2. Java框架----SSH整合回顾

    1,新建工程,类型为Web Project,设置默认编码为UTF-8,并创建如下文件夹 1,Source Folder 1,src 项目源码 2,config 配置文件 3,test 单元测试 2,普 ...

  3. 传说中的WCF(12):服务器回调有啥用

    你说,服务器端回调有啥用呢?这样问,估计不好回答,是吧.不急,先讨论一个情景. 假设现有服务器端S,客户端A开始连接S并调用相关操作,其中有一个操作,在功能上有些特殊,调用后无法即时回复,因为在服务器 ...

  4. 小奇模拟赛9.13 by hzwer

    2015年9月13日NOIP模拟赛 by hzwer    (这是小奇=> 小奇挖矿(explo) [题目背景] 小奇要开采一些矿物,它驾驶着一台带有钻头(初始能力值w)的飞船,按既定路线依次飞 ...

  5. JAVA实现Excel导出数据(以写好的Excel模版导出)

    工作中经常会有将后台数据以Excel导出的功能. 简单的方法有将response的contentType设置为application/vnd.ms-excel: 或在JSP页面直接设置成: <% ...

  6. Junit单元测试学习笔记一

    我们在编写大型程序的时候,需要写成千上万个方法或函数,这些函数的功能可能很强大,但我们在程序中只用到该函数的一小部分功能,并且经过调试可以确定,这一小部分功能是正确的.但是,我们同时应该确保每一个函数 ...

  7. ios开发多线程--GCD

    引言 虽然GCD使用很广,而且在面试时也经常问与GCD相关的问题,但是我相信深入理解关于GCD知识的人肯定不多,大部分都是人云亦云,只是使用过GCD完成一些很简单的功能.当然,使用GCD完成一些简单的 ...

  8. 图解TCP/IP读书笔记(一)

    图解TCP/IP读书笔记(一) 第一章 网络基础知识 本学期的信安概论课程中有大量的网络知识,其中TCP/IP占了相当大的比重,让我对上学期没有好好学习计算机网络这门课程深感后悔.在老师的推荐下开始阅 ...

  9. jQuery:balloon气泡提示插件

    插件下载地址:http://file.urin.take-uma.net/jquery.balloon.js-Demo.html <!DOCTYPE html PUBLIC "-//W ...

  10. MyBatis学习总结_18_MyBatis与Hibernate区别

    也用了这么久的Hibernate和MyBatis了,一直打算做一个总结,就他们之间的优缺点说说我自己的理解: 首先,Hibernate是一个ORM的持久层框架,它使用对象和我们的数据库建立关系,在Hi ...