// 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. 如何用 Parse 和 Swift 搭建一个像 Instagram 那样的应用?(2)

    [编者按]本篇文章作者是 Reinder de Vries,既是一名企业家,也是优秀的程序员,发表多篇应用程序的博客.本篇文章中,作者主要介绍了如何基于 Parse 特点,打造一款类似 Instagr ...

  2. tomcat 多开设置 需要需改的3个端口

    启动多tomcat需要需改的3个端口 我所用Tomcat服务器都为zip版,非安装版.以两个为例: 安装第二个Tomcat完成后,到安装目录下的conf子目录中打开server.xml文件,查找以下三 ...

  3. nefu 120 梅森素数

    题意:给出p(1<p<=62),让你求Mp=2^p-1是否为梅森素数. 梅森素数:若p为素数,且Mp=2^p-1也是素数,则Mp为梅森素数.若p为合数,Mp=2^p-1一定为合数若p为素数 ...

  4. swift函数和初始化控件(// MARK:分割线)

    import UIKit , , , )         view.backgroundColor = UIColor.redColor()         self.view.addSubview( ...

  5. POJ 3468 A Simple Problem with Integers(线段树)

    题目链接 题意 : 给你n个数,进行两种操作,第一种是将a到b上所有元素都加上c,第二种是查询a到b上所有元素之和输出. 思路 : 线段树,以前写过博客,但是现在在重刷,风格改变,,所以重新写一篇.. ...

  6. 浅说Java中的反射机制(二)

    写过一篇Java中的反射机制,不算是写,应该是抄了,因为那是别人写的,这一篇也是别人写的,摘抄如下: 引自于Java基础--反射机制的知识点梳理,作者醉眼识朦胧.(()为我手记) 什么是反射? 正常编 ...

  7. python--httplib模块使用

    httplib是一个相对底层的http请求模块,其上有专门的包装模块,如urllib内建模块,goto等第三方模块,但是封装的越高就越不灵 活,比如urllib模块里请求错误时就不会返回结果页的内容, ...

  8. MyEclipse — Maven+Spring+Struts+Hibernate 整合 [学习笔记-5]

    测试项目 目录结构

  9. 【poj3358】消因子+BSGS 或 消因子+欧拉定理 两种方法

    题意:给你一个分数,求它在二进制下的循环节的长度,还有第一个循环节从哪一位开始. For example, x = 1/10 = 0.0001100110011(00110011)w and 0001 ...

  10. 叠罗汉I

    叠罗汉是一个著名的游戏,游戏中一个人要站在另一个人的肩膀上.同时我们应该让下面的人比上面的人更高一点.已知参加游戏的每个人的身高,请编写代码计算通过选择参与游戏的人,我们多能叠多少个人.注意这里的人都 ...