Click here to Skip to main content
15,892,161 members

Response to: LogonUser method and the administrative privilegies

Revision 1
Is it for local Users or in a Windows-Domain?

May you just use the administrator for executing some methods?

C#
private bool doSomeThingWithAdministrativePrivilegs()
        {
            IntPtr token;

            if (!NativeMethods.LogonUser(
                <$user>, //Administrator or User with administrativ privilegs
                <$domain>, //if no domain avalible set computername System.Environment.MachineName it was i think .ToString()...
                <$password>,
                NativeMethods.LogonType.NewCredentials,
                NativeMethods.LogonProvider.Default,
                out token))
            {
                throw new Win32Exception();
            }

            try
            {
                IntPtr tokenDuplicate;

                if (!NativeMethods.DuplicateToken(
                    token,
                    NativeMethods.SecurityImpersonationLevel.Impersonation,
                    out tokenDuplicate))
                {
                    throw new Win32Exception();
                }

                try
                {
                    using (WindowsImpersonationContext impersonationContext =
                        new WindowsIdentity(tokenDuplicate).Impersonate())
                    {
                        // DO the stuff privilegs needed in here...
                    }
                }
                finally
                {
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        if (!NativeMethods.CloseHandle(tokenDuplicate))
                        {
                            return false;
                            //throw new Win32Exception();
                        }
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    if (!NativeMethods.CloseHandle(token))
                    {
                        return false;
                        //throw new Win32Exception();
                    }
                }
            }
            return true;
        }
Posted 11-Aug-11 3:11am by diialer.
Tags: