473,569 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 10909
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
ImpersonationCo ntext.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(st ring domain, string userName, string password)

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

UndoImpersonati on() // Reverts to original process Identity

The UndoImpersonati on() 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>Impersonat eValidUser()</varcan impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpers onation()</varmethod
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Se curity.Permissi ons">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAt tribute(Securit yAction.Demand, Name = "FullTrust" )]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Bo olean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}
// Set up Impersonation via InterOp
private const int LOGON32_LOGON_I NTERACTIVE = 2;
private const int LOGON32_PROVIDE R_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security .Principal.Wind owsImpersonatio nContext
ImpersonationCo ntext;

[SuppressUnmanag edCodeSecurityA ttribute()]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
private static extern int LogonUser(Strin g lpszUserName, String
lpszDomain,Stri ng lpszPassword,in t dwLogonType, int dwLogonProvider ,ref
IntPtr phToken);

[SuppressUnmanag edCodeSecurityA ttribute()]
[DllImport("adva pi32.dll",
CharSet=System. Runtime.Interop Services.CharSe t.Auto, SetLastError=tr ue)]
private extern static int DuplicateToken( IntPtr hToken, int
impersonationLe vel, ref IntPtr hNewToken);

[DllImport("kern el32.dll",
CharSet=System. Runtime.Interop Services.CharSe t.Auto)]
private unsafe static extern int FormatMessage(i nt dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
private extern static bool CloseHandle(Int Ptr handle);

/// <summary mod="unsafe static" type="System.St ring">
/// 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_DE NIED
//throw new System.Componen tModel.Win32Exc eption(errorCod e);

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(d wFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArgument s);
if (0 == retVal)
{
throw new Exception("Fail ed 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">D omain 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(st ring domain, string userName, string password)
{
ImpersonateVali dUser(userName, domain, password);
}

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

/// <summary type="System.Bo olean">
/// Impersonate a User
/// </summary>
/// <param name="userName" >User Name of User to impersonate</param>
/// <param name="domain">D omain of User to impersonate</param>
/// <param name="password" >Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateVali dUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIde ntity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonati on();

if (LogonUser(user Name, domain, password,
LOGON32_LOGON_I NTERACTIVE, LOGON32_PROVIDE R_DEFAULT, ref _Token) != 0)
{
if (DuplicateToken (_Token, 2, ref _TokenDuplicate ) != 0)
{
_TempWindowsIde ntity = new
WindowsIdentity (_TokenDuplicat e);
ImpersonationCo ntext =
_TempWindowsIde ntity.Impersona te();
if (ImpersonationC ontext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.Handl eError(ex);
return false;
}
}
/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonati on()
{
if (ImpersonationC ontext != null) ImpersonationCo ntext.Undo();
ImpersonationCo ntext = null;
}

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

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.

"Ciaran O''Donnell" <Ci************ @discussions.mi crosoft.comwrot e in
message news:C0******** *************** ***********@mic rosoft.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
ImpersonationCo ntext.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(st ring domain, string userName, string password)

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

UndoImpersonati on() // Reverts to original process Identity

The UndoImpersonati on() 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>Impersonat eValidUser()</varcan impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpers onation()</varmethod
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Se curity.Permissi ons">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAt tribute(Securit yAction.Demand, Name = "FullTrust" )]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Bo olean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}
// Set up Impersonation via InterOp
private const int LOGON32_LOGON_I NTERACTIVE = 2;
private const int LOGON32_PROVIDE R_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security .Principal.Wind owsImpersonatio nContext
ImpersonationCo ntext;

[SuppressUnmanag edCodeSecurityA ttribute()]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
private static extern int LogonUser(Strin g lpszUserName, String
lpszDomain,Stri ng lpszPassword,in t dwLogonType, int dwLogonProvider ,ref
IntPtr phToken);

[SuppressUnmanag edCodeSecurityA ttribute()]
[DllImport("adva pi32.dll",
CharSet=System. Runtime.Interop Services.CharSe t.Auto, SetLastError=tr ue)]
private extern static int DuplicateToken( IntPtr hToken, int
impersonationLe vel, ref IntPtr hNewToken);

[DllImport("kern el32.dll",
CharSet=System. Runtime.Interop Services.CharSe t.Auto)]
private unsafe static extern int FormatMessage(i nt dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
private extern static bool CloseHandle(Int Ptr handle);

/// <summary mod="unsafe static" type="System.St ring">
/// 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_DE NIED
//throw new System.Componen tModel.Win32Exc eption(errorCod e);

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(d wFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArgument s);
if (0 == retVal)
{
throw new Exception("Fail ed 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">D omain 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(st ring domain, string userName, string password)
{
ImpersonateVali dUser(userName, domain, password);
}

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

/// <summary type="System.Bo olean">
/// Impersonate a User
/// </summary>
/// <param name="userName" >User Name of User to impersonate</param>
/// <param name="domain">D omain of User to impersonate</param>
/// <param name="password" >Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateVali dUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIde ntity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonati on();

if (LogonUser(user Name, domain, password,
LOGON32_LOGON_I NTERACTIVE, LOGON32_PROVIDE R_DEFAULT, ref _Token) != 0)
{
if (DuplicateToken (_Token, 2, ref _TokenDuplicate ) != 0)
{
_TempWindowsIde ntity = new
WindowsIdentity (_TokenDuplicat e);
ImpersonationCo ntext =
_TempWindowsIde ntity.Impersona te();
if (ImpersonationC ontext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.Handl eError(ex);
return false;
}
}
/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonati on()
{
if (ImpersonationC ontext != null) ImpersonationCo ntext.Undo();
ImpersonationCo ntext = null;
}

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

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.

"Ciaran O''Donnell" <Ci************ @discussions.mi crosoft.comwrot e in
message news:C0******** *************** ***********@mic rosoft.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
ImpersonationCo ntext.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
2734
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 configure IIS to Integrated Windows Security for a particular site? I don't want users to have to log in again to the site as they have already logged in...
2
1511
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. It would be very easy for me to simply use IIS Admin to remove anonymous access to that file and to create a new account on the web server and give...
3
1595
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 the post or get-method. What I don't know is how to post those values one asp-page further through code, so without anyone having to press any button....
2
2628
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 is how do I set the username and password? Say the username is bob@home.com and the password is onions, how do I set this? The values could be...
7
11083
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 are no problems using the Chilkat FTP component, or connecting and browsing manually with a variety of FTP clients. The code I'm using is:
18
3396
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 dozens of examples of how to authenticate users against Active Directory, but AD seems to be a different animal than Sun Java System Directory Server....
0
1517
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 Credentials to the current network DefaultCredentials. With lds_WebService
1
8671
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 service was written with java. Since this web services uses soap I should have no problems consuming it from other languages, although I'm having a...
9
6262
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 only has read access to the users table so that users can log in. Once a user has been logged in successfully I want to escalate that user's access...
0
7694
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7921
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
6278
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5504
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.