473,416 Members | 1,546 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

System.IO alternative user credentials? Is it possible?

I am trying to figure out how to pass set of credentials to System.IO

Challenge is:
App is running under one set of credentials, but via GUI user have a chance
to enter another set. I would like to be able to use supplied credentials
with System.IO versus using default credentials that app is running under.

So far I am forced to use WMI which is less convenient and slower then
System.IO, but it's providing me with "Connection Options"

Any suggestions are welcome

Sep 8 '06 #1
3 10885
You need to call the LogonUser api function in advapi.dll in the windows api
to get a security token (as an IntPtr), then you need to call DuplicateToken
(cant remember the dll but I think its Kernal32.dll) to make it a primary
token which you can then use to start impersonating the user with the
WindowsIdentity class in the framework. When impersonating, all the code the
runs under the windows identity your impersonating until you call
ImpersonationContext.Undo

I know this isnt a full answer but it should be enough to run a few
fruitfull searches
Ciaran O'Donnell

"Dmitry" wrote:
I am trying to figure out how to pass set of credentials to System.IO

Challenge is:
App is running under one set of credentials, but via GUI user have a chance
to enter another set. I would like to be able to use supplied credentials
with System.IO versus using default credentials that app is running under.

So far I am forced to use WMI which is less convenient and slower then
System.IO, but it's providing me with "Connection Options"

Any suggestions are welcome
Sep 9 '06 #2
Here's a managed class (Impersonator) I wrote that presents a fairly easy
impersonation interface. It employs the Windows API, including both
kernel32.dll and advapi32.dll, but does not expose the unmanaged activity.
It simply has 2 methods and 2 constructors:

Impersonator() // Parameterless constructor

// Constructor. Attempts to impersonate user with domain credentials
Impersonator(string domain, string userName, string password)

// Attempts to impersonate user with domain credentials
ImpersonateValidUser(string domain, string userName, string password)

UndoImpersonation() // Reverts to original process Identity

The UndoImpersonation() method is called by the Finalizer, in case it is not
called in the code.

************************************************** ****************
/// <summary>
/// Provides Impersonation capability.
/// </summary>
/// <remarks>This class can impersonate any user in a domain. The
/// parameterized Constructor will attempt to impersonate a User according
to
/// the Domain, User Name, and Password passed to it. In addition, the
/// <var>ImpersonateValidUser()</varcan impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpersonation()</varmethod
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Security.Permissions">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Boolean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}
// Set up Impersonation via InterOp
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security.Principal.WindowsImpersonationCont ext
ImpersonationContext;

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern int LogonUser(String lpszUserName, String
lpszDomain,String lpszPassword,int dwLogonType, int dwLogonProvider,ref
IntPtr phToken);

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o, SetLastError=true)]
private extern static int DuplicateToken(IntPtr hToken, int
impersonationLevel, ref IntPtr hNewToken);

[DllImport("kernel32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);

/// <summary mod="unsafe static" type="System.String">
/// Formats and returns an error message
/// corresponding to the input <paramref name="errorCode"/>.
/// </summary>
/// <param name="errorCode">A Win32 Error code</param>
/// <returns>The string translation of the <paramref
name="errorCode"/></returns>
public unsafe static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

//int errorCode = 0x5; //ERROR_ACCESS_DENIED
//throw new System.ComponentModel.Win32Exception(errorCode);

int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS;

IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;

int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " +
errorCode + ". ");
}
return lpMsgBuf;
}

/// <summary>
/// Constructor. Initializes <var>Domain</var>, <var>UserName</var>, and
/// <var>Password</var>
/// </summary>
/// <param name="domain">Domain of impersonated User account</param>
/// <param name="userName">User name of impersonated User
account</param>
/// <param name="password">Password of impersonated User account</param>
public Impersonator(string domain, string userName, string password)
{
ImpersonateValidUser(userName, domain, password);
}

/// <summary>
/// Constructor.
/// </summary>
public Impersonator()
{
}

/// <summary type="System.Boolean">
/// Impersonate a User
/// </summary>
/// <param name="userName">User Name of User to impersonate</param>
/// <param name="domain">Domain of User to impersonate</param>
/// <param name="password">Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateValidUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIdentity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonation();

if (LogonUser(userName, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _Token) != 0)
{
if (DuplicateToken(_Token, 2, ref _TokenDuplicate) != 0)
{
_TempWindowsIdentity = new
WindowsIdentity(_TokenDuplicate);
ImpersonationContext =
_TempWindowsIdentity.Impersonate();
if (ImpersonationContext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.HandleError(ex);
return false;
}
}
/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonation()
{
if (ImpersonationContext != null) ImpersonationContext.Undo();
ImpersonationContext = null;
}

/// <summary mod="~">
/// Destructor. Ensures that Impersonation is cancelled.
/// </summary>
~Impersonator()
{
UndoImpersonation();
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.

"Ciaran O''Donnell" <Ci************@discussions.microsoft.comwrote in
message news:C0**********************************@microsof t.com...
You need to call the LogonUser api function in advapi.dll in the windows
api
to get a security token (as an IntPtr), then you need to call
DuplicateToken
(cant remember the dll but I think its Kernal32.dll) to make it a primary
token which you can then use to start impersonating the user with the
WindowsIdentity class in the framework. When impersonating, all the code
the
runs under the windows identity your impersonating until you call
ImpersonationContext.Undo

I know this isnt a full answer but it should be enough to run a few
fruitfull searches
Ciaran O'Donnell

"Dmitry" wrote:
>I am trying to figure out how to pass set of credentials to System.IO

Challenge is:
App is running under one set of credentials, but via GUI user have a
chance
to enter another set. I would like to be able to use supplied credentials
with System.IO versus using default credentials that app is running
under.

So far I am forced to use WMI which is less convenient and slower then
System.IO, but it's providing me with "Connection Options"

Any suggestions are welcome

Sep 10 '06 #3
W.O.W. (!)

Thanks. It will take me a little while to dog through the code. I do not
like to use code I done completely understand, and it's a lot of new idea
here for me to dig through.

Thank you
"Kevin Spencer" wrote:
Here's a managed class (Impersonator) I wrote that presents a fairly easy
impersonation interface. It employs the Windows API, including both
kernel32.dll and advapi32.dll, but does not expose the unmanaged activity.
It simply has 2 methods and 2 constructors:

Impersonator() // Parameterless constructor

// Constructor. Attempts to impersonate user with domain credentials
Impersonator(string domain, string userName, string password)

// Attempts to impersonate user with domain credentials
ImpersonateValidUser(string domain, string userName, string password)

UndoImpersonation() // Reverts to original process Identity

The UndoImpersonation() method is called by the Finalizer, in case it is not
called in the code.

************************************************** ****************
/// <summary>
/// Provides Impersonation capability.
/// </summary>
/// <remarks>This class can impersonate any user in a domain. The
/// parameterized Constructor will attempt to impersonate a User according
to
/// the Domain, User Name, and Password passed to it. In addition, the
/// <var>ImpersonateValidUser()</varcan impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpersonation()</varmethod
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Security.Permissions">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Boolean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}
// Set up Impersonation via InterOp
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security.Principal.WindowsImpersonationCont ext
ImpersonationContext;

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern int LogonUser(String lpszUserName, String
lpszDomain,String lpszPassword,int dwLogonType, int dwLogonProvider,ref
IntPtr phToken);

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o, SetLastError=true)]
private extern static int DuplicateToken(IntPtr hToken, int
impersonationLevel, ref IntPtr hNewToken);

[DllImport("kernel32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);

/// <summary mod="unsafe static" type="System.String">
/// Formats and returns an error message
/// corresponding to the input <paramref name="errorCode"/>.
/// </summary>
/// <param name="errorCode">A Win32 Error code</param>
/// <returns>The string translation of the <paramref
name="errorCode"/></returns>
public unsafe static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

//int errorCode = 0x5; //ERROR_ACCESS_DENIED
//throw new System.ComponentModel.Win32Exception(errorCode);

int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS;

IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;

int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " +
errorCode + ". ");
}
return lpMsgBuf;
}

/// <summary>
/// Constructor. Initializes <var>Domain</var>, <var>UserName</var>, and
/// <var>Password</var>
/// </summary>
/// <param name="domain">Domain of impersonated User account</param>
/// <param name="userName">User name of impersonated User
account</param>
/// <param name="password">Password of impersonated User account</param>
public Impersonator(string domain, string userName, string password)
{
ImpersonateValidUser(userName, domain, password);
}

/// <summary>
/// Constructor.
/// </summary>
public Impersonator()
{
}

/// <summary type="System.Boolean">
/// Impersonate a User
/// </summary>
/// <param name="userName">User Name of User to impersonate</param>
/// <param name="domain">Domain of User to impersonate</param>
/// <param name="password">Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateValidUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIdentity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonation();

if (LogonUser(userName, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _Token) != 0)
{
if (DuplicateToken(_Token, 2, ref _TokenDuplicate) != 0)
{
_TempWindowsIdentity = new
WindowsIdentity(_TokenDuplicate);
ImpersonationContext =
_TempWindowsIdentity.Impersonate();
if (ImpersonationContext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.HandleError(ex);
return false;
}
}
/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonation()
{
if (ImpersonationContext != null) ImpersonationContext.Undo();
ImpersonationContext = null;
}

/// <summary mod="~">
/// Destructor. Ensures that Impersonation is cancelled.
/// </summary>
~Impersonator()
{
UndoImpersonation();
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.

"Ciaran O''Donnell" <Ci************@discussions.microsoft.comwrote in
message news:C0**********************************@microsof t.com...
You need to call the LogonUser api function in advapi.dll in the windows
api
to get a security token (as an IntPtr), then you need to call
DuplicateToken
(cant remember the dll but I think its Kernal32.dll) to make it a primary
token which you can then use to start impersonating the user with the
WindowsIdentity class in the framework. When impersonating, all the code
the
runs under the windows identity your impersonating until you call
ImpersonationContext.Undo

I know this isnt a full answer but it should be enough to run a few
fruitfull searches
Ciaran O'Donnell

"Dmitry" wrote:
I am trying to figure out how to pass set of credentials to System.IO

Challenge is:
App is running under one set of credentials, but via GUI user have a
chance
to enter another set. I would like to be able to use supplied credentials
with System.IO versus using default credentials that app is running
under.

So far I am forced to use WMI which is less convenient and slower then
System.IO, but it's providing me with "Connection Options"

Any suggestions are welcome


Sep 14 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Bruno | last post by:
Do you know how to get windows login variables (i.e. the LOGON_USER server variable) from ASP without having to fill in the challenge response message box that automatically appears when you...
2
by: Brian Madden | last post by:
Hello Everyone, This is sort of a followup to the protecting files question I asked earlier today. I would like to protect a file so that only certain users could download it from my website....
3
by: Avlan | last post by:
Still new with asp, and I feel I haven't yet captured the logic of it completely ;-P I know how to post values to another asp-page through the use of a form and a submit-button, combined with...
2
by: Tim Cowan | last post by:
Hi, I am using .NET 2.0 and I want to send mail that uses SMTP authorization. I have found this in the help: client.Credentials = System.Net.CredentialCache.DefaultCredentials; My question...
7
by: Mark Rae | last post by:
Hi, Has anyone successfully used the FTP stuff in the System.Net namespace against a VMS FTP server? I'm trying to do this at the moment and can't even get a directory listing, although there...
18
by: troywalker | last post by:
I am new to LDAP and Directory Services, and I have a project that requires me to authenticate users against a Sun Java System Directory Server in order to access the application. I have found...
0
by: ndskim | last post by:
Currently I have the Web Services Proxy code generated by the WSDL.Exe command line. My Web app consists of ASP.NET in VB 2005 version. Here is what I have in the sample code: ' Set Proxy...
1
by: bugnthecode | last post by:
Hi, I am trying to put together a small app that uses one of my company's web service. Originally I interfaced with this web service using java, and have the example code. I believe the web...
9
by: Gordon | last post by:
I want to add a feature to a project I'm working on where i have multiple users set up on my Postgres database with varying levels of access. At the bare minimum there will be a login user who...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.