Share this page 

Detect if current user is ADMIN using JNA (Windows) Tag(s): JNA Environment Security


JNA (Java Native Access) provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code - no JNI or native code is required.

This HowTo detects if the current user is a member the Administrator group. This is done by checking the "well-known" sid.


import com.sun.jna.platform.win32.Advapi32Util;



// https://github.com/twall/jna#readme

//    you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar



public class IsAdmin {



    public static void main(String[] args) {

        boolean isAdmin = false;

        Advapi32Util.Account[] groups = Advapi32Util.getCurrentUserGroups();

        for (Advapi32Util.Account group : groups) {

           if ("S-1-5-32-544".equals(group.sidString)) {

              isAdmin = true;

              break;

           }

        }



        if (isAdmin){

           System.out.println("Current User is ADMIN");

        }

        else{

           System.out.println("Current User is not ADMIN");

        }

    }

}

Instead of hard-coding the well-known string representation of the Administrator group, we can used the Windows API exposed by JNA to verify the value.


import com.sun.jna.platform.win32.Advapi32;

import com.sun.jna.platform.win32.Advapi32Util;

import com.sun.jna.platform.win32.WinNT.PSIDByReference;

import com.sun.jna.platform.win32.WinNT.WELL_KNOWN_SID_TYPE;



// https://github.com/twall/jna#readme

//    you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar



public class IsAdmin {



    public static void main(String[] args) {

        boolean isAdmin = false;

        Advapi32Util.Account[] groups = Advapi32Util.getCurrentUserGroups();

        for (Advapi32Util.Account group : groups) {

           PSIDByReference sid = new PSIDByReference();

           Advapi32.INSTANCE.ConvertStringSidToSid(group.sidString, sid);

           if (Advapi32.INSTANCE.IsWellKnownSid(sid.getValue(),

                  WELL_KNOWN_SID_TYPE.WinBuiltinAdministratorsSid)) {

              isAdmin = true;

              break;

           }

        }

        if (isAdmin){

           System.out.println("Current User is ADMIN");

        }

        else{

           System.out.println("Current User is not ADMIN");

        }

    }

}

See also this HowTo.