简体   繁体   English

在java中获取登录用户名

[英]Get login username in java

How can I get the username/login name in Java?如何在 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.当我尝试运行此代码时,出现SecurityException Could someone please tell me whether I'm heading in the right direction, and help me to understand the problem.有人可以告诉我我是否朝着正确的方向前进,并帮助我理解问题。

System.getProperty("user.name")

in Unix:在Unix中:

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

in Windows:在 Windows 中:

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

in Solaris:在 Solaris 中:

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

inspired by @newacct 's answer, a code that can be compiled in any platform:受到@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 ) );
}

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: System.getProperty("user.name") 不是一个好的安全选项,因为该环境变量可能是伪造的: C:\\ set USERNAME="Joe Doe" java ... // will give you 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 and greater. JDK 1.5 及更高版本。

I use it within an applet, and it has to be signed.我在小程序中使用它,并且必须对其进行签名。 info source信息来源

Using JNA its simple:使用 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 https://github.com/java-native-access/jna

The 'set Username="Username" ' is a temporary override that only exists as long as the cmd windows is still up, once it is killed off, the variable loses value. 'set Username="Username" '是一个临时覆盖,只有在 cmd 窗口仍然存在时才存在,一旦它被杀死,变量就会失去价值。 So i think the所以我认为

System.getProperty("user.name"); System.getProperty("用户名");

is still a short and precise code to use.仍然是一个简短而精确的代码。

System.getenv().get("USERNAME"); - works on windows ! - 适用于窗户!

In environment properties you have the information you need about computer and host!在环境属性中,您有您需要的有关计算机和主机的信息! I am saying again!我再说一遍! Works on WINDOWS !适用于WINDOWS!

Below is a solution for WINDOWS ONLY以下是仅适用于 WINDOWS 的解决方案

In cases where the application (like Tomcat) is started as a windows service, the System.getProperty("user.name") or System.getenv().get("USERNAME") return the user who started the service and not the current logged in user name.在应用程序(如 Tomcat)作为 Windows 服务启动的情况下, System.getProperty("user.name") 或 System.getenv().get("USERNAME") 返回启动服务的用户而不是当前登录的用户名。

Also in Java 9 the NTSystem etc classes will not be accessible同样在 Java 9 中,将无法访问 NTSystem 等类

So workaround for windows: You can use wmic , so you have to run the below command因此 Windows 的解决方法:您可以使用wmic ,因此您必须运行以下命令

wmic ComputerSystem get UserName

If available, this will return output of the form:如果可用,这将返回以下形式的输出:

UserName
{domain}\{logged-in-user-name}

Note: For windows you need to use cmd /c as a prefix, so below is a crude program as an example:注意:windows 需要使用 cmd /c 作为前缀,下面以粗略的程序为例:

    Process exec = Runtime.getRuntime().exec("cmd /c wmic ComputerSystem get UserName".split(" "));
    System.out.println(exec.waitFor());
    try (BufferedReader bw = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
        System.out.println(bw.readLine() + "\n" + bw.readLine()+ "\n" + bw.readLine());
    }

I tested in linux centos我在linux centos上测试过

Map<String, String> env = System.getenv();   
for (String envName : env.keySet()) { 
 System.out.format("%s=%s%n", envName, env.get(envName)); 
}

System.out.println(env.get("USERNAME")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM