views:

1848

answers:

3

How can I get the username/login name in java ?

I 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 (LoginException le){
      System.out.println("LoginException: " + le.getMessage());
     }catch(SecurityException se){
      System.out.println("SecurityException: " + se.getMessage());
     }

but I get a SecurityException. I'm new to all this, so I don't know whether I'm using the right stuff, but badly, or I'm going in the right direction.

Any hint will help.

+8  A: 
System.getProperty("user.name") ?
dfa
+1 you can print the System.properties to get a lot of informations the VM is initialized with
Markus Lausberg
Thanks! I come from Flash/actionscript...so I've got a looooooot to cover :)
George Profenza
+1  A: 

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()
newacct
This code goes against Java's philosophy of write once, run anywhere (introduction of OS specific code), and secondly, it creates a dependency on Sun's implementation of Java.
Jin Kim
Trying to get the username is by definition platform-specific. A JVM running on a single-user system might not have a username at all.
Chinmay Kanchi
+2  A: 

Hi, System.getProperty("user.name") is not a good security option since that environment variable could be faked: C:\ set USERNAME="Joe Doe" java ... // will give you System.getProperty("user.name") You ought to do:

com.sun.security.auth.module.NTSystem NTSystem = new com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());

JDK 1.5 and greater.

I use it within an applet, and it has to be signed. info source

pdjota
Quite handy +1! Thanks!
George Profenza