在java中获取登录用户名

2022-08-31 10:07:02

如何在Java中获取用户名/登录名?

这是我尝试过的代码...

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


答案 1
System.getProperty("user.name");

答案 2

在Unix中:

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

在窗口中:

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

在索拉里斯:

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

推荐