在java中获取login用户名

我怎样才能在Java中获得用户名/login名?

这是我试过的代码…

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()); } 

我尝试运行此代码时遇到SecurityException 。 有人能告诉我是否正朝着正确的方向前进,并帮助我理解这个问题。

 System.getProperty("user.name") 

在Unix中:

 new com.sun.security.auth.module.UnixSystem().getUsername() 

在Windows中:

 new com.sun.security.auth.module.NTSystem().getName() 

在Solaris中:

 new com.sun.security.auth.module.SolarisSystem().getUsername() 

System.getProperty(“user.name”)不是一个好的安全选项,因为该环境variables可能是伪造的:C:\ set USERNAME =“Joe Doe”java … //会给你System.getProperty(“user。名字“)你应该这样做:

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

JDK 1.5和更高版本。

我在一个小程序中使用它,并且必须签名。 信息来源

@newacct的回答启发,一个可以在任何平台上编译的代码:

 String osName = System.getProperty( "os.name" ).toLowerCase(); String className = null; String methodName = "getUsername"; if( osName.contains( "windows" ) ){ className = "com.sun.security.auth.module.NTSystem"; methodName = "getName"; } else if( osName.contains( "linux" ) ){ className = "com.sun.security.auth.module.UnixSystem"; } else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){ className = "com.sun.security.auth.module.SolarisSystem"; } if( className != null ){ Class<?> c = Class.forName( className ); Method method = c.getDeclaredMethod( methodName ); Object o = c.newInstance(); System.out.println( method.invoke( o ) ); } 

使用JNA其简单:

 String username = Advapi32Util.getUserName(); System.out.println(username); Advapi32Util.Account account = Advapi32Util.getAccountByName(username); System.out.println(account.accountType); System.out.println(account.domain); System.out.println(account.fqn); System.out.println(account.name); System.out.println(account.sidString); 

https://github.com/java-native-access/jna

'设置用户名='用户名''是一个临时覆盖,只有当cmd窗口仍然存在时才存在,一旦被closures,variables将失去值。 所以我认为

System.getProperty( “user.name”);

仍然是一个简短而精确的代码。

System.getenv().get("USERNAME"); – 在Windows上工作!

在环境属性你有你需要的信息关于电脑和主机! 我再说一遍! 在WINDOWS上工作!