如何检索用户登录ID

时间:2009-09-10 10:24:35

标签: java

我需要检索登录到服务器的用户的登录ID。我想用Java做。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

您可以在环境中找到它:

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

但是安全管理员可能会阻止这种情况(例如,从applet调用时)!

答案 1 :(得分: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 :(得分: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 );
}