2009-09-10 85 views
0

我需要检索登录到服务器的用户的登录ID。我想用Java来做。我怎样才能做到这一点?如何检索用户登录ID

+2

您应该添加您正在使用的是什么类型的服务器,可能是什么类型的身份验证。 – 2009-09-10 10:33:04

回答

0

如果您转储System.properties,您会发现一个名为user.name的属性。这应该或多或少是启动JDK进程的OS用户。

下面是一个代码片段,帮助

Properties props = System.getProperties(); 
Enumeration e = props.propertyNames(); 
while(e.hasMoreElements()){ 
    Object key = e.nextElement(); 
    Object val = props.getProperty(key.toString()); 
    System.out.println("key:"+ key +" val:"+ val); 
} 
0

这是平台相关的。 你在说什么类型的服务器?

以下是返回您正在运行您的应用程序的用户的名称。 我发现这段代码在http://www.exampledepot.com/egs/javax.security.auth.login/GetLogin.html

try { 
    String loginAppName = "GetLoginNameUnix"; 

    // If the application is run on NT rather than Unix, use this name 
    loginAppName = "GetLoginNameNT"; 

    // Create login context 
    LoginContext lc = new LoginContext(loginAppName, 
     new com.sun.security.auth.callback.TextCallbackHandler()); 

    // Retrieve the information on the logged-in user 
    lc.login(); 

    // Get the authenticated subject 
    Subject subject = lc.getSubject(); 

    // Get the subject principals 
    Principal principals[] = (Principal[])subject.getPrincipals().toArray(new Principal[0]); 
    for (int i=0; i<principals.length; i++) { 
     if (principals[i] instanceof com.sun.security.auth.NTUserPrincipal 
       || principals[i] instanceof com.sun.security.auth.UnixPrincipal) { 
      String loggedInUserName = principals[i].getName(); 
     } 
    } 
} catch (LoginException e) { 
    // Login failed 
} 

根据该网站,你需要的模块加载它的配置。

2

您可以在环境中找到它:

String login = System.getProperty("user.name"); 

但安全管理器可以防止这种情况(例如从applet调用时)!