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 4086398
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T18:43:16+00:00 2026-05-20T18:43:16+00:00

My Winforms app set permissions based on the group membership found in the current

  • 0

My Winforms app set permissions based on the group membership found in the current process.

I just made a unit test in MSTEST.

I’d like to run it as other users so I can verify the expected behavior.

Here’s what I’m kind of shooting for:

    [TestMethod]
    public void SecuritySummaryTest1()
    {
        Impersonate(@"SomeDomain\AdminUser", password);
        var target = new DirectAgentsSecurityManager();
        string actual = target.SecuritySummary;
        Assert.AreEqual(
            @"Default=[no]AccountManagement=[no]MediaBuying=[no]AdSales=[no]Accounting=[no]Admin=[YES]", actual);
    }
    [TestMethod]
    public void SecuritySummaryTest2()
    {
        Impersonate(@"SomeDomain\AccountantUser", password);
        var target = new DirectAgentsSecurityManager();
        string actual = target.SecuritySummary;
        Assert.AreEqual(
            @"Default=[no]AccountManagement=[YES]MediaBuying=[no]AdSales=[no]Accounting=[YES]Admin=[NO]", actual);
    }
  • 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-20T18:43:17+00:00Added an answer on May 20, 2026 at 6:43 pm
    public class UserCredentials
    {
        private readonly string _domain;
        private readonly string _password;
        private readonly string _username;
    
        public UserCredentials(string domain, string username, string password)
        {
            _domain = domain;
            _username = username;
            _password = password;
        }
    
        public string Domain { get { return _domain; } }
        public string Username { get { return _username; } }
        public string Password { get { return _password; } }
    }
    public class UserImpersonation : IDisposable
    {
        private readonly IntPtr _dupeTokenHandle = new IntPtr(0);
        private readonly IntPtr _tokenHandle = new IntPtr(0);
        private WindowsImpersonationContext _impersonatedUser;
    
        public UserImpersonation(UserCredentials credentials)
        {
            const int logon32ProviderDefault = 0;
            const int logon32LogonInteractive = 2;
            const int securityImpersonation = 2;
    
            _tokenHandle = IntPtr.Zero;
            _dupeTokenHandle = IntPtr.Zero;
    
            if (!Advapi32.LogonUser(credentials.Username, credentials.Domain, credentials.Password,
                                    logon32LogonInteractive, logon32ProviderDefault, out _tokenHandle))
            {
                var win32ErrorNumber = Marshal.GetLastWin32Error();
    
                // REVIEW: maybe ImpersonationException should inherit from win32exception
                throw new ImpersonationException(win32ErrorNumber, new Win32Exception(win32ErrorNumber).Message,
                                                 credentials.Username, credentials.Domain);
            }
    
            if (!Advapi32.DuplicateToken(_tokenHandle, securityImpersonation, out _dupeTokenHandle))
            {
                var win32ErrorNumber = Marshal.GetLastWin32Error();
    
                Kernel32.CloseHandle(_tokenHandle);
                throw new ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", credentials.Username,
                                                 credentials.Domain);
            }
    
            var newId = new WindowsIdentity(_dupeTokenHandle);
            _impersonatedUser = newId.Impersonate();
        }
    
        public void Dispose()
        {
            if (_impersonatedUser != null)
            {
                _impersonatedUser.Undo();
                _impersonatedUser = null;
    
                if (_tokenHandle != IntPtr.Zero)
                    Kernel32.CloseHandle(_tokenHandle);
    
                if (_dupeTokenHandle != IntPtr.Zero)
                    Kernel32.CloseHandle(_dupeTokenHandle);
            }
        }
    }
    
    internal static class Advapi32
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL,
                                                 out IntPtr DuplicateTokenHandle);
    
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword,
                                            int dwLogonType, int dwLogonProvider, out IntPtr phToken);
    }
    
    internal static class Kernel32
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return : MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr hObject);
    }
    

    I didn’t include the implementation of ImpersonationException but it’s not important. It doesn’t do anything special.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create a WinForms app that takes a screenshot on a set
Today I'm playing with localization. I have a winforms app where I've set localizable
I have a test winforms app with ThreadExceptionHandler that displays a message box when
In our current WinForms app, we are displaying millions of records in ListView, using
My WinForms app uses Process.Start() to open files in their native app. I want
I'm making a WinForms app with a ListView set to detail so that several
I'm writing an winforms app that needs to set internet explorer's proxy settings and
I have a small WinForms app that utilizes a BackgroundWorker object to perform a
I have a C# winforms app with a form for user preferences. An admin
I have a C# WinForms app with an About box. I am putting the

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.