Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7585593
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T19:12:50+00:00 2026-05-30T19:12:50+00:00

Here is the scenario: 1. The app is already running as a local admin

  • 0

Here is the scenario:
1. The app is already running as a local admin
2. It impersonates as a domain account, which is also an admin on the local box
3. While impersonated, the app is trying to create a regkey under the key that has Full Control to the Administrators group for “This key and subkeys.”

This step fails with UnauthorizedException “Access to registry key ..” is denied.
Now, if I explicitly ACL the regkey for the domain user, the creation of the regkey goes through. But then this solution defeats the purpose of being in the admin group.

Any ideas what could go wrong here?

EDIT: I’m running on Windows Server 2008 R2. I figured this issue is due to UAC enabled. LogonUser method returns a restricted token, which does not have elevated access to the registry. Any ideas on how to get an elevated access using LogonUser method?

Here is how I call it:
IntPtr token = IntPtr.Zero;
LogonUser(username, domain, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, out token)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T19:12:51+00:00Added an answer on May 30, 2026 at 7:12 pm

    I will suggest several things to check:

    • You should attribute your class (that executes impersonation) for a full trust mode request, which you can do using

      [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
      
    • Also, you should import “advapi32.dll” and LogonUser to be used later.

    • Finally, you should get a safe token handle (inherited from SafeHandleZeroOrMinusOneIsInvalid, which provides a base class for Win32 safe handle implementations in which the value of either 0 or -1 indicates an invalid handle).
    • Within this you should be calling it like this (*using LOGON32_LOGON_INTERACTIVE since BATCH will not work*)

      LogonUser(userName, domainName, password, 2, 0, out safeTokenHandle);
      

    After getting a handle, you should use it to perform any action:

        WindowsIdentity impid = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
    

    After getting it, encapsulate your actions:

        using (WindowsImpersonationContext imp = impid.Impersonate())
        { 
          // myActions
        }
    

    This should enable you to do it correctly and detect how it went.

    I have now tried to do this in an ASP.NET application and succeded. Here is a working code for an MVC application controller:

    using System;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Web.Mvc;
    using Microsoft.Win32;
    using Microsoft.Win32.SafeHandles;
    
    namespace StackOimpersonationExample.Controllers
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public class HomeController : Controller
        {
            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
                                                int dwLogonType, int dwLogonProvider, out TokenHandle phToken);
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            public static extern bool CloseHandle(IntPtr handle);
    
            public ActionResult Index()
            {
                ViewBag.Message = "This line contains status info.";
    
    
                #region ImpersonateTestUserAndWriteToRegistry
    
                try
                {
                    const string domainName = "W8CP";
                    const string userName = "testadmin";
                    const string password = "sxt";
    
                    TokenHandle tokenHandle;
                    bool returnValue = LogonUser(userName, domainName, password, 2, 0, out tokenHandle);
    
                    if (returnValue == false)
                    {
                        int retVal = Marshal.GetLastWin32Error();
                        ViewBag.Message = String.Format("Failed logon: {0}", retVal);
                        throw new System.ComponentModel.Win32Exception(retVal);
                    }
                    using (tokenHandle)
                    {
                        ViewBag.Message = "Logon successful!";
                        var newId = new WindowsIdentity(tokenHandle.DangerousGetHandle());
                        using (newId.Impersonate())
                        {
                            RegistryKey parentKey = Registry.LocalMachine;
                            RegistryKey softwareKey = parentKey.OpenSubKey("SOFTWARE", true);
                            if (softwareKey != null)
                            {
                                RegistryKey subKey = softwareKey.CreateSubKey("StackAnswer");
    
                                subKey.SetValue("CreatedAs", WindowsIdentity.GetCurrent().Name, RegistryValueKind.String);
                                subKey.SetValue("Website", "http://codecentral.org", RegistryValueKind.String);
                                subKey.SetValue("Email", "tonci.jukic@gmail.com", RegistryValueKind.String);
    
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Message += String.Format(" Exception: " + ex.Message);
                }
                #endregion
    
                return View();
            }
        }
    
        public sealed class TokenHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            private TokenHandle(): base(true){}
    
            [DllImport("kernel32.dll")]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            [SuppressUnmanagedCodeSecurity]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CloseHandle(IntPtr handle);
    
            protected override bool ReleaseHandle()
            {
                return CloseHandle(handle);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here's the scenario. I'm debugging my own app (C/C++) which is using some library
Here's the scenario: On my iPhone app (OS 3.1.2), I've got view 1 which
Here's a scenario: I have a java front end (RCP/SWT) app which currently has
Here is the scenario: I'm writing an app that will watch for any changes
I am planning on developing my specific voip app for android. Here's the scenario:
Tackling a strange scenario here. We use a proprietary workstation management application which uses
Here is my scenario: I have my-jsf-app.war (JSF 1.2 application) and daos-and-entities.har (Hibernate 3.3.1)
Here's my scenario: I'm using the WebBrowser control in a WinForms app to display
Here's the scenario I have an ASP.NET 4.0 application which has a LOT of
Here is my scenario: 1) in my activity, user pushes Authorize button. 2) app

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.