impersonate a user
// 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的更多相关文章
- How to Programmatically Impersonate Users in SharePoint
Sometimes when creating SharePoint web or console applications, you may need to execute specific c ...
- <!--转换office时需要此配置 --> <identity impersonate="true" />
1.需要对Office 进行操作时 ,添加权限 <!--转换office时需要此配置 --> <identity impersonate="true" /> ...
- 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,加入如下配置项 < ...
- 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 ...
- User root is not allowed to impersonate anonymous
User root is not allowed to impersonate anonymous ava.lang.RuntimeException: org.apache.hadoop.ipc.R ...
- 【原创】大叔经验分享(38)beeline连接hiveserver2报错impersonate
beeline连接hiveserver2报错 Error: Could not open client transport with JDBC Uri: jdbc:hive2://localhost: ...
- 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 ...
- 如果应用程序正在通过 <identity impersonate="true"/> 模拟,则标识将为匿名用户(通常为 IUSR_MACHINENAME)或经过身份验证的请求用户。
在配置文件中添加 <identity impersonate= "true " userName= "Administrator " pass ...
- 关于 web.config impersonate 帐号模拟
1.模拟 IIS 验证的帐户或用户 若要在收到 ASP.NET 应用程序中每个页的每个请求时模拟 Microsoft Internet 信息服务 (IIS) 身份验证用户,必须在此应用程序的 Web. ...
随机推荐
- Wamp Mysql错误消息 语言设置
Wamp Mysql错误消息 语言设置 http://my.oschina.net/wandershi/blog/264347 打开my.ini 找到 [wampmysqld] port = 33 ...
- DF学Mysql(三)——索引操作
概要: 数据库对象索引其实与书的目录非常相似,主要是为了提高从表中检索数据的速度. 由于数据存储在数据库表中,所以索引是创建在数据库表对象上的,由表中的一个字段或多个字段生成的键组成,这些键存储在数据 ...
- 取得DisplayMerics手机屏幕大小的应用
DisplayMerics:A structure describing general information about a display, such as its size, density, ...
- C# WinForm窗口最小化到系统托盘
* C# WinForm窗口最小化到系统托盘http://hi.baidu.com/kfxtgtqyapouyze/item/8ccfdcd5a174a7312a35c7c3 主要功能:(1).程序启 ...
- 机器学习之神经网络模型-下(Neural Networks: Representation)
3. Model Representation I 1 神经网络是在模仿大脑中的神经元或者神经网络时发明的.因此,要解释如何表示模型假设,我们不妨先来看单个神经元在大脑中是什么样的. 我们的大脑中充满 ...
- poj 2349(最小生成树应用)
题目链接:http://poj.org/problem?id=2349 思路:由于有S个专门的通道,我们可以先求一次最小生成树,然后对于最小生成树上的边从大到小排序,前S-1条边用S-1个卫星通道连接 ...
- shell脚本替换文件中字符
1.将当前目录下包含jack串的文件中,jack字符串替换为tom sed -i "s/jack/tom/g" `grep "jack" -rl ./` 2.将 ...
- hibernate初次配置问题
1.自动创建表结构 在hibernate.cfg.xml配置文件中修改 <property name="hibernate.hbm2ddl.auto">update&l ...
- lintcode:最长上升子序列
题目 最长上升子序列 给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度. 样例 给出[5,4,1,2,3],这个LIS是[1,2,3],返回 3 给出[4,2,4,5,3,7],这个L ...
- exploring the http Object
form.html <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset=&q ...