Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
George Profenza Avatar asked Apr 28 '09 12:04

George Profenza


People also ask

How to get username of user in java?

getProperty("user.name") or System. getenv(). get("USERNAME") return the user who started the service and not the current logged in user name.


2 Answers

System.getProperty("user.name"); 
like image 92
dfa Avatar answered Sep 18 '22 13:09

dfa


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() 
like image 20
newacct Avatar answered Sep 20 '22 13:09

newacct