472,353 Members | 972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 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 10664
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...
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...
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...
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 =...
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...
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...
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...
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,...
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...
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...

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.