// 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. ArrayList和Iterator的用法

    import java.util.ArrayList; import java.util.Iterator; public class ArrayListTest { public static vo ...

  2. C Primer Plus之结构和其他数据形式

    声明和初始化结构指针 声明结构化指针,例如: struct guy * him; 初始化结构指针(如果barney是一个guy类型的结构),例如: him = &barney; 注意:和数组不 ...

  3. C Primer Plus之指针

    c之精髓——指针(pointer)——用来存储地址的变量.一般来讲,指针是一个其数值为地址的变量(或更一般地说是一个数据对象). 一元运算符&可以取得变量的存储地址,一个变量的地址可以被看作是 ...

  4. JS中的this好神奇,都把我弄晕了

    一.this的常见判断: 1.函数预编译过程 this —> window 2.全局作用域里 this —> window 3.call/apply 可以改变函数运行时this指向 4.o ...

  5. Jmeter之Bean shell使用(二)

    上一篇Jmeter之Bean shell使用(一)简单介绍了下Jmeter中的Bean shell,本文是对上文的一个补充,主要总结下常用的几种场景和方法,相信这些基本可以涵盖大部分的需求.本节内容如 ...

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

    示例数据库test,用户信息表

  7. Gradle Goodness: Skip Building Project Dependencies

    If we use Gradle in a multi-module project we can define project dependencies between modules. Gradl ...

  8. 多页面打印--web print

    背景:项目中要求做在一个页面中通过选择网址来打印多个页面的内容的功能 原理:通过iframe把各网址的页面内容加载进来,通过iframe.contentWindow拿到iframe的window对象, ...

  9. C#之使用AutoResetEvent实现线程的顺序执行

    前几天一朋友问我如何实现线程的顺序执行,说真的,虽然看过CLR这本书,也把线程部分拜读了两遍,但是这个问题出来之后还是没有一个思路.今天在搜索资料的时候无意中再次看到AutoResetEvent这个东 ...

  10. centos使用fuse挂载NTFS

    FUSE:用户空间文件系统(Filesystem in Userspace),是Linux 中用于挂载某些网络空间,如SSH,到本地文件系统的模块.如果装的是双系统,centOS并不支持ntfs分区, ...