mlivme2
mlivme2

Reputation: 27

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:

How can I do that

Upvotes: 1

Views: 515

Answers (1)

Jason
Jason

Reputation: 3960

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

Upvotes: 1

Related Questions