简体   繁体   中英

How can I check if my program is really running as an administrator?

We have a setup program that runs an MSBuild script which imports a self-signed certificate in the local computer account's Personal/My certificate store. I am in the Administrators group on the server where setup is being run, and UAC is not enabled. When I run my script, and import the certificate, I am unable to use it in IIS. Process Monitor shows access denied errors when I try to assign it to a website.

However, when I explicitly run my script as an administrator (right-click and choose "Run As Administrator"), the certificate is imported successfully , and I can use it in IIS. This is extremely bizarre to me.

How can I tell if my script/program is running as an administrator? I'd like to add a check to the setup script that fails if it detects it isn't running with this weird "Run As Administrator" privilege. I would prefer an answer in C#/.NET.

I've tried using GetTokenInformation , to get the elevation type, but that only works when UAC is enabled.

Using System.Security.Principal.WindowsIdentity.IsInRole(WindowsBuiltInRole.Administrator) return true in a regular and "elevated" prompt.

I've compared the Owner, User, and Group SIDS exposed by System.Security.Principal.WindowsIdentity.GetCurrent , and the list is the same in a regular and "elevated" prompt.

Check further into the thread that @Rahul posted... you'll find this link which includes code (albeit in VB.Net, but I've pasted a conversion to c# below) that should do the trick.

Here's the relevant function in c# (you'll need a using statement for System.Security.Principal):

public bool IsRunningAsLocalAdmin()
{
    WindowsIdentity cur = WindowsIdentity.GetCurrent();
    foreach (IdentityReference role in cur.Groups) {
        if (role.IsValidTargetType(typeof(SecurityIdentifier))) {
            SecurityIdentifier sid = (SecurityIdentifier)role.Translate(typeof(SecurityIdentifier));
            if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid)) {
                return true;
            }

        }
    }

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM