Get login username in java
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.
Solution 1:
System.getProperty("user.name");
Solution 2:
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()