0

I have a windows forms application that will be run in both domain and on non-domain (local desktop) environments. I'm trying to understand how the windows security works in these different environments. I need to programmatically identify when the windows user running my application as an Administrator which I'm assuming is different for domain and local environments (and possibly when the UAC is in control?? ).

I'm also a little confused as to whether the UAC supersedes a domain log in if turned on?

I expect most remote users of the product will be set as local Administrators too, and restricted by the UAC.

How do you check for privileges under these conditions? (vb.net app but c# is also fine - thank you)

Cheers, Tim.

Tim Windsor
  • 319
  • 1
  • 5
  • 17

2 Answers2

1
Public Function isWindowsAdministrator() As Boolean
    My.User.InitializeWithWindowsUser()
    If My.User.IsAuthenticated Then
        If My.User.IsInRole(Microsoft.VisualBasic.ApplicationServices.BuiltInRole.Administrator) Then
            Return True
        End If
    End If
    Return False
End Function

There is probably a nonVB/'pure' NET alternative, I just dont know the equivalents. There is also a way to test if the user can elevate to Admin, but it is a PInvoke, messy win32 thing, and doesnt actually elevate, just tests.

UAC will still pop up, the above just lets you know in advance if the user can authorize.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • thanks for your solutions - I had tried this, but missed the 'initializeWithWindowsUser and hence got no response. I was trying to get the username and the domain into a Principal.WindowsIdentity and go from there. I would have marked with answer but I've found another solution and got it to work which I'd like to share also. Thanks again – Tim Windsor Oct 03 '13 at 09:15
0

Vb.Net:

Public Function IsUserAnAdmin() As Boolean End Function

C#:

[DllImport("shell32.dll")] public static extern bool IsUserAnAdmin();

As you can see returns a Boolean by calling IsUserAnAdmin (you could obviously use an alias). for clarity I believe this works in all scenarios I mentioned but I haven't fully completed my Domain testing.... yet

Tim Windsor
  • 319
  • 1
  • 5
  • 17
  • that method is short and sweet...and deprecated in favor of `CheckTokenMembership`. There is also the issue of split tokens (some privs are stripped out). There is way to check for that, but it requires 3 or 4 interops and calls to `advapi32.dll`. It is very thorough and reliable, but I dont like the interop calls. For simplicity, I prefer the NET version I posted and instances where it may fail are not my fault. BTW 'accept' doesnt mean you promise to use the answer, just that it works http://stackoverflow.com/about – Ňɏssa Pøngjǣrdenlarp Oct 03 '13 at 14:56