I need to check if the current Logon Windows account is an Administrator of the PC.
If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
'Is Admin
Else
'Isn't Admin
End If
This code work fine but if i lunch the code with RUN AS "another account" the code dont do the right job becouse take the account that lunch the code not the Windows account that is logged in.
With this code i can see the current Windows User logged in:
Dim Coll As ManagementObjectCollection
Dim LogonName As String
Dim GetName As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Coll = GetName.[Get]()
LogonName = DirectCast(Coll.Cast(Of ManagementBaseObject)().First()("UserName"), String)
Dim CleanName() As String = Split(LogonName, "\")
So in the string LogonName i'll have the Windows user name account that is logged in but how can i check if is an Administrator?
You can use System.Security.Principle
namespace for this task. I wrote a function in a separate class you can use if you would like or move the function...
This is the class...
Option Strict On
Option Explicit On
Imports System.Security.Principal
Public Class SecurityClass
#Region "Functions"
Public Shared Function IsAdministrator() As Boolean
Dim isAdmin As Boolean = False
Try
Dim user As IIdentity = WindowsIdentity.GetCurrent()
Dim principal As New WindowsPrincipal(CType(user, WindowsIdentity))
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator)
Return isAdmin
Catch ex As Exception
Return isAdmin
End Try
End Function
#End Region
End Class
To use the class and function, just simply call it where ever needed. I used a messagebox to show it for my test using a button click event.
Private Sub btnIsAdmin_Click(sender As Object, e As EventArgs) Handles btnIsAdmin.Click
If SecurityClass.IsAdministrator Then
MessageBox.Show("Current user is an Administrator")
Else
MessageBox.Show("Current user is not Administrator")
End If
End Sub
Public Function UserIsAdmin(ByVal userName As String) As Boolean
Dim groupName As String = "administrators" '<--You can localize this'
Dim isAdmin As Boolean
Using context As PrincipalContext = New PrincipalContext(ContextType.Machine)
Dim gfilter As GroupPrincipal = GroupPrincipal.FindByIdentity(context, groupName)
If gfilter IsNot Nothing Then
Dim members = gfilter.GetMembers
For Each member In members
If String.Compare(member.Name, userName, True) = 0 Then
isAdmin = True
End If
Next
End If
End Using
Return isAdmin
End Function