如何在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());
}
Run Code Online (Sandbox Code Playgroud)
SecurityException当我尝试运行此代码时,我得到了一个.有人可以告诉我,我是否正朝着正确的方向前进,并帮助我理解这个问题.
dfa*_*dfa 204
System.getProperty("user.name")
Run Code Online (Sandbox Code Playgroud)
new*_*cct 29
在Unix中:
new com.sun.security.auth.module.UnixSystem().getUsername()
Run Code Online (Sandbox Code Playgroud)
在Windows中:
new com.sun.security.auth.module.NTSystem().getName()
Run Code Online (Sandbox Code Playgroud)
在Solaris中:
new com.sun.security.auth.module.SolarisSystem().getUsername()
Run Code Online (Sandbox Code Playgroud)
cel*_*owm 16
受@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 ) );
}
Run Code Online (Sandbox Code Playgroud)
pdj*_*ota 15
System.getProperty("user.name")不是一个好的安全选项,因为该环境变量可能是伪造的: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());
Run Code Online (Sandbox Code Playgroud)
JDK 1.5及更高版本.
我在applet中使用它,它必须签名. 信息来源
使用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);
Run Code Online (Sandbox Code Playgroud)
https://github.com/java-native-access/jna
| 归档时间: |
|
| 查看次数: |
155842 次 |
| 最近记录: |