Share this page 

Get the current Windows Username Tag(s): JNA Security

In application :

public class Test {

    public static void main(String args[]) {

      System.out.println( System.getProperty("") );



will print the current user.

But it's not a good idea to use this technique to secure your application because it is very easy to spoof ... you just need to specify the "" value from the command line when starting the JVM!

> java Test


As an alternative with JDK1.5,

public class Test {

  public static void main(String args[]) { NTSystem = new






this will return the current username as known by Windows. The drawback here is that we are using a class from a com.sun.* package which is not a good practice and may break in a future Java release.

A better solution is to call the directly the Windows API using JNA!

import com.sun.jna.Native;

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

import com.sun.jna.ptr.IntByReference;

import com.sun.jna.win32.W32APIOptions;

// required jars : jna-3.5.1.jar , platform-3.5.1.jar

public class WindowsUtils {

   private WindowsUtils() {}

   static final Secur32 secur32 =

         (Secur32) Native.loadLibrary("secur32", Secur32.class, W32APIOptions.DEFAULT_OPTIONS);

   public static String getCurrentUserName() {

      char[] userNameBuf = new char[10000];

      IntByReference size = new IntByReference(userNameBuf.length);

      boolean result = secur32.GetUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameSamCompatible, userNameBuf, size);

      if (!result)

          throw new IllegalStateException("Cannot retreive name of the currently logged-in user");

      return new String(userNameBuf, 0, size.getValue());


   public static void main(String[] args) {

      System.out.println(WindowsUtils.getCurrentUserName()); // output [domain]/[user]



See also Authenticate a user (JNA/Windows)