2009-09-10 87 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調用時)!