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("user.name") ); } }
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 "user.name" value from the command line when starting the JVM!
> java -Duser.name=Elvis.Presley Test Elvis.Presley
public class Test { public static void main(String args[]) { com.sun.security.auth.module.NTSystem NTSystem = new com.sun.security.auth.module.NTSystem(); System.out.println(NTSystem.getName()); System.out.println(NTSystem.getDomain()); } }
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] } }
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com