How can I get the username/login name in Java?
This is the code I have tried...
try{ LoginContext lc = new LoginContext(appName,new TextCallbackHandler()); lc.login(); Subject subject = lc.getSubject(); Principal principals[] = (Principal[])subject.getPrincipals().toArray(new Principal[0]); for (int i=0; i<principals.length; i++) { if (principals[i] instanceof NTUserPrincipal || principals[i] instanceof UnixPrincipal) { String loggedInUserName = principals[i].getName(); } } } catch(SecurityException se){ System.out.println("SecurityException: " + se.getMessage()); }
I get a SecurityException
when I try to run this code. Could someone please tell me whether I'm heading in the right direction, and help me to understand the problem.
getProperty("user.name") or System. getenv(). get("USERNAME") return the user who started the service and not the current logged in user name.
System.getProperty("user.name");
in Unix:
new com.sun.security.auth.module.UnixSystem().getUsername()
in Windows:
new com.sun.security.auth.module.NTSystem().getName()
in Solaris:
new com.sun.security.auth.module.SolarisSystem().getUsername()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With