mnp13
asked on
Access a server file using impersonation
I have to access an internal file from a web application and need to use impersonation to get access to the server.
I have not been sucessful so far, and the "help" files for .NET are somewhat lacking...
it's an asp.Net application with C# code behind.
Thank you,
Michelle
I have not been sucessful so far, and the "help" files for .NET are somewhat lacking...
it's an asp.Net application with C# code behind.
Thank you,
Michelle
ASKER
please leave it active, I am still working on the project. thank you.
ASKER
It's not working and not giving me an error message or any indication of why...
it throws me to the "catch" at this line: impersonationContext =
((System.Security.Principa l.WindowsI dentity)Us er.Identit y).Imperso nate();
it throws me to the "catch" at this line: impersonationContext =
((System.Security.Principa
Can you show me how you are using this code?
Bob
Bob
ASKER
I'll post the section of code I"m useing on Monday, as it is on my work computer. Thanks!
ASKER
using System.Security.Principal;
...code...
System.Security.Principal. WindowsImp ersonation Context impersonationContext;
impersonationContext =
((System.Security.Principa l.WindowsI dentity)Us er.Identit y).Imperso nate();
if (servPath.Equals("Null"))
{
this.hypServPDF.Enabled = false;
this.hypServPDF.Text = "not available";
}
else
{
this.hypServPDF.Enabled = true;
this.hypServPDF.Text = "Download";
this.hypServPDF.NavigateUr l = servPath.ToString();
this.hypServPDF.Target = "bill";
}
impersonationContext.Undo( );
...code...
System.Security.Principal.
impersonationContext =
((System.Security.Principa
if (servPath.Equals("Null"))
{
this.hypServPDF.Enabled = false;
this.hypServPDF.Text = "not available";
}
else
{
this.hypServPDF.Enabled = true;
this.hypServPDF.Text = "Download";
this.hypServPDF.NavigateUr
this.hypServPDF.Target = "bill";
}
impersonationContext.Undo(
Here is a class converted from VB.NET (untested):
using System;
using System.Runtime.InteropServ ices;
using System.Security.Principal;
using System.Security.Permission s;
public class WindowsImpersonator
{
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll") ]
private static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref string lpBuffer, int nSize, ref IntPtr Arguments);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEV EL, ref IntPtr DuplicateTokenHandle);
private WindowsImpersonationContex t m_impersonatedUser;
private static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BU FFER = 256;
int FORMAT_MESSAGE_IGNORE_INSE RTS = 512;
int FORMAT_MESSAGE_FROM_SYSTEM = 4096;
int messageSize = 255;
string lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BU FFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSE RTS;
IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, ref prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " + errorCode.ToString() + ". ");
}
return lpMsgBuf;
}
public void Impersonate(string domainName, string userName, string password)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
const int SecurityImpersonation = 2;
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
try
{
bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error( );
throw new Exception(string.Format("E rror: [{0}] {1}", ret, GetErrorMessage(ret)));
}
bool retVal = DuplicateToken(tokenHandle , SecurityImpersonation, ref dupeTokenHandle);
if (!retVal)
{
CloseHandle(tokenHandle);
throw new Exception("Exception thrown in trying to duplicate token.");
}
WindowsIdentity newId = new WindowsIdentity(dupeTokenH andle);
m_impersonatedUser = newId.Impersonate();
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
if (dupeTokenHandle != IntPtr.Zero)
{
CloseHandle(dupeTokenHandl e);
}
}
catch (Exception ex)
{
Console.WriteLine(("Except ion occurred. " + ex.Message));
}
}
public void Undo()
{
m_impersonatedUser.Undo();
}
public string CurrentName
{
get { return WindowsIdentity.GetCurrent ().Name; }
}
}
Bob
using System;
using System.Runtime.InteropServ
using System.Security.Principal;
using System.Security.Permission
public class WindowsImpersonator
{
[DllImport("advapi32.dll",
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")
private static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref string lpBuffer, int nSize, ref IntPtr Arguments);
[DllImport("kernel32.dll",
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll",
private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEV
private WindowsImpersonationContex
private static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BU
int FORMAT_MESSAGE_IGNORE_INSE
int FORMAT_MESSAGE_FROM_SYSTEM
int messageSize = 255;
string lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BU
IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, ref prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " + errorCode.ToString() + ". ");
}
return lpMsgBuf;
}
public void Impersonate(string domainName, string userName, string password)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
const int SecurityImpersonation = 2;
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
try
{
bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE,
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error(
throw new Exception(string.Format("E
}
bool retVal = DuplicateToken(tokenHandle
if (!retVal)
{
CloseHandle(tokenHandle);
throw new Exception("Exception thrown in trying to duplicate token.");
}
WindowsIdentity newId = new WindowsIdentity(dupeTokenH
m_impersonatedUser = newId.Impersonate();
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
if (dupeTokenHandle != IntPtr.Zero)
{
CloseHandle(dupeTokenHandl
}
}
catch (Exception ex)
{
Console.WriteLine(("Except
}
}
public void Undo()
{
m_impersonatedUser.Undo();
}
public string CurrentName
{
get { return WindowsIdentity.GetCurrent
}
}
Bob
ASKER
That is about 10 miles over my head. where do I put that, and where do I put the file path it is suppoed to be accessing?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok, I'll give it a go...
I'm off of work until Monday, but I will try it and repond then.
I'm off of work until Monday, but I will try it and repond then.
see http://support.microsoft.com/?scid=306158