473,406 Members | 2,217 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,406 software developers and data experts.

Impersonation not working in ASP.NET

I am trying to get response back using impersonated user

I am loggedon as user "xyz" on domain "DEV", I created an empty website which at session start in global.asax writes current user(System.Security.Principal.WindowsIdentity.Get Current()) in a file.

I am calling default.aspx from Nunit(using asp extensions) using system.net.webrequest as follows


Expand|Select|Wrap|Line Numbers
  1.     ImpersonateLogonUser.ClsImpersonateUser impersonate = new ImpersonateLogonUser.ClsImpersonateUser();
  2.     impersonate.ImpersonateUser("TestUser1", "DEV", "");
  3.     System.Net.WebRequest request = System.Net.WebRequest.Create("http://localhost:4445/Default.aspx");
  4.     request.GetResponse();
  5.  
I am expecting System.Security.Principal.WindowsIdentity.GetCurre nt() to write TestUser1 in file but it is writing "xyz"


I have tested impersonation is working if I call the code from within SessinStart in global.asax


Impersonation code is as follows
Expand|Select|Wrap|Line Numbers
  1.     using System;
  2.     using System.Collections;
  3.     using System.ComponentModel;
  4.     using System.Data;
  5.     using System.Runtime.InteropServices;  // DllImport
  6.     using System.Security.Principal; // WindowsImpersonationContext
  7.     using System.Security.Permissions; // PermissionSetAttribute
  8.  
  9.     namespace ImpersonateLogonUser
  10.     {
  11.         public enum SECURITY_IMPERSONATION_LEVEL : int
  12.         {
  13.             SecurityAnonymous = 0,
  14.             SecurityIdentification = 1,
  15.             SecurityImpersonation = 2,
  16.             SecurityDelegation = 3
  17.         }
  18.         public class ClsImpersonateUser
  19.         {    
  20.  
  21.             // obtains user token
  22.             [DllImport("advapi32.dll", SetLastError = true)]
  23.             public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
  24.                 int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  25.  
  26.             // closes open handes returned by LogonUser
  27.             [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  28.             public extern static bool CloseHandle(IntPtr handle);
  29.  
  30.             // creates duplicate token handle
  31.             [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  32.             public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
  33.                 int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
  34.  
  35.  
  36.             private System.Security.Principal.WindowsImpersonationContext newUser;
  37.  
  38.             /// <summary>
  39.             /// Required designer variable.
  40.             /// </summary>
  41.             private System.ComponentModel.Container components = null;
  42.  
  43.  
  44.             /// <summary>
  45.             /// Attempts to impersonate a user.  If successful, returns
  46.             /// a WindowsImpersonationContext of the new users identity.
  47.             /// </summary>
  48.             /// <param name="sUsername">Username you want to impersonate</param>
  49.             /// <param name="sDomain">Logon domain</param>
  50.             /// <param name="sPassword">User's password to logon with</param></param>
  51.             /// <returns></returns>
  52.             public WindowsImpersonationContext ImpersonateUser(string sUsername, string sDomain, string sPassword)
  53.             {
  54.                 // initialize tokens
  55.                 IntPtr pExistingTokenHandle = new IntPtr(0);
  56.                 IntPtr pDuplicateTokenHandle = new IntPtr(0);
  57.                 pExistingTokenHandle = IntPtr.Zero;
  58.                 pDuplicateTokenHandle = IntPtr.Zero;
  59.  
  60.                 // if domain name was blank, assume local machine
  61.                 if (sDomain == "")
  62.                     sDomain = System.Environment.MachineName;
  63.  
  64.                 try
  65.                 {
  66.                     string sResult = null;
  67.  
  68.                     const int LOGON32_PROVIDER_DEFAULT = 0;
  69.  
  70.                     // create token
  71.                     const int LOGON32_LOGON_INTERACTIVE = 2;
  72.                     //const int SecurityImpersonation = 2;
  73.  
  74.                     // get handle to token
  75.                     bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
  76.                         LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
  77.  
  78.                     // did impersonation fail?
  79.                     if (false == bImpersonated)
  80.                     {
  81.                         int nErrorCode = Marshal.GetLastWin32Error();
  82.                         sResult = "LogonUser() failed with error code: " + nErrorCode + "\r\n";
  83.  
  84.                         // show the reason why LogonUser failed
  85.                         //MessageBox.Show(this, sResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  86.                     }
  87.  
  88.                     // Get identity before impersonation
  89.                     sResult += "Before impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
  90.  
  91.                     bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
  92.  
  93.                     // did DuplicateToken fail?
  94.                     if (false == bRetVal)
  95.                     {
  96.                         int nErrorCode = Marshal.GetLastWin32Error();
  97.                         CloseHandle(pExistingTokenHandle); // close existing handle
  98.                         sResult += "DuplicateToken() failed with error code: " + nErrorCode + "\r\n";
  99.  
  100.                         // show the reason why DuplicateToken failed
  101.                         //MessageBox.Show(this, sResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  102.                         return null;
  103.                     }
  104.                     else
  105.                     {
  106.                         // create new identity using new primary token
  107.                         WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
  108.                         WindowsImpersonationContext impersonatedUser = newId.Impersonate();
  109.  
  110.                         // check the identity after impersonation
  111.                         sResult += "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
  112.  
  113.                         //MessageBox.Show(this, sResult, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  114.                         return impersonatedUser;
  115.                     }
  116.                 }
  117.                 catch (Exception ex)
  118.                 {
  119.                     throw ex;
  120.                 }
  121.                 finally
  122.                 {
  123.                     // close handle(s)
  124.                     if (pExistingTokenHandle != IntPtr.Zero)
  125.                         CloseHandle(pExistingTokenHandle);
  126.                     if (pDuplicateTokenHandle != IntPtr.Zero)
  127.                         CloseHandle(pDuplicateTokenHandle);
  128.                 }
  129.             }
  130.         }
  131.     }
  132.  
Feb 22 '12 #1
0 1514

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tom Wells | last post by:
My server admin and I are trying to figure out how to get impersonation working to be able to upload a file from the client browser thru the web server to a network file server. My network ID for...
15
by: Patrick | last post by:
I set my web.config as follows: <authentication mode="Windows" /> <identity impersonate="true" /> Logon to my ASP.NET website as a user who can authenticate to the target database. 1) Works...
1
by: William Oliveri | last post by:
Hello all, I have a working example of Impersonation where I receive a token and a true response for a specific user. However, if I try to access a drive that has only that user's permission to...
1
by: bennett | last post by:
In order for my ASP.Net application to access a database using my privileged account, I was told to set up an app using Integrated Windows authentication and to use impersonation. I set the app to...
11
by: Phil | last post by:
Hi, I've currently setup a local user as described in: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnne...
4
by: David Cablalero | last post by:
I have a windows service which every night checks a SQL Server database for some data and business rules. The application can access different DBs with the same structure, to tell the service which...
0
by: Elroyskimms | last post by:
I need to execute a batch file via ASP.Net. In my VB.Net code, I'm using System.Diagnostics.Process to call the batch file and its appropriate command line arguments. I'm using...
6
by: David C | last post by:
I was testing impersonation on a web site and added the line below to my web.config file. Now it fails with the message The current identity (DOMAIN01\LegalWeb) does not have write access to...
0
by: ChopStickr | last post by:
I have a custom control that is embedded (using the object tag) in an html document. The control takes a path to a local client ini file. Reads the file. Executes the program specified in...
0
by: sillz | last post by:
On Apr 8, 2:00 pm, sillz <beth.sto...@gmail.comwrote: I never could get this to work. The oracle account tested fine. I ended up creating a new account in Windows with the right permissions...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
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
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
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.