To get the name of the current user in a Java program, you can simply fetch the value of the user.name
system property:
System.getProperty("user.name");
But how secure is that? Can a user executing the program easily set this property to an arbitrary value (using a command-line argument of the JVM, for example) for common runtime environments? Can a user easily spoof this user name?
I ask because I am writing a command-line program that can be run by anyone, but allows some privileged operations only if the user is a special administrative user.
Note that since Java 11 the user.name
property is effectively read only once the program starts, so malicious program code can not spoof it.