简体   繁体   中英

c# application authorization based on Windows current user

I write a small application and I need to add some authorization security tips.

Simple Example: I have a WinForm that contain two buttons: btnAdd and btnDelete. I want that:

  • if the current user is in the Administrator group, both the two buttons above will be displayed

  • else (if not in the Administrator group (like like guess account)) only btnAdd will be displayed.

How can I do that

You should be able to construct a WindowsPrincipal object, then just check if the user is in the role you expect, and use the return value to set the button to visible or not. Something like the below

using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
    WindowsPrincipal principal = new WindowsPrincipal(identity);

    // using WindowsBuiltInRole.Administrator or "BUILTIN\\Administrators" should work
    btnAdd.Visible = principal.IsInRole(WindowsBuiltInRole.Administrator);
}

The updated code works, I've tested this, where I'm a local admin, since you want to test the current user, WindowsIdentity.GetCurrent() is actually cleaner.

If you need to confirm whether or not you are an admin on the machine, you can either check the group membership through MMC, but if there is any domain groups involved and you don't have access you won't be able to check this through MMC unless you have access to AD.

A sure way to verify if a user is a member of group is running the below in a command prompt window

Get members of local Administrators group:

net localgroup administrators

Get members of the domain group: this is necessary if for example, mydomain\\WorkstationAdmins is a member of the local Administrators group and userId is a member of mydomain\\WorkstationAdmins (thus an admin of the wokstation)

net group "WorkstationAdmins" /domain

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