2014-03-02 35 views
0

我正在查找使用用戶的IP地址查詢LDAP的方法。使用IP地址屬性的LDAP查詢

當有人使用瀏覽器時,瀏覽器會一起發送其IP地址。 我想使用該IP地址查詢LDAP以查找該IP地址所屬的用戶名。

我已經設法使用Java中的LDAP連接到AD。

+1

奇怪的要求。用戶只能從一個IP地址登錄?你甚至*有目錄中的用戶的IP地址?如果是這樣,在什麼屬性? – EJP

+1

請注意,_browser_不會一直髮送其IP地址,但_server_會在每個請求上記錄遠程客戶端IP。這不是很可靠:認爲(反向)代理,NAT等。 – mvreijn

回答

1

請閱讀EJP的評論,並首先重新考慮您的要求。不管

爲什麼你想這一點,你將需要採取幾個步驟:

  • 尋找到你的用戶上下文(LDAP容器)。 AD默認爲cn=Users,dc=your,dc=domain,dc=com
  • 標識包含IP地址的LDAP屬性(比方說networkAddress現在)
  • 檢索從HTTP請求中的IP地址(假設String userAddress
  • 使用濾波器(&(objectClass=inetOrgPerson)(networkAddress=userAddress))爲(用戶)對象執行所述查詢

你的Java代碼應該是這樣的(假設你有一個活LdapConnection對象爲你所提到的):

public void getUserByIp(LdapContext ctx, String userAddress) 
{ 
    // Replace with your context and domain name 
    String userContext = "cn=Users,dc=your,dc=domain,dc=com"; 

    String filter = "(&(objectClass=inetOrgPerson)(networkAddress="+userAddress+"))"; 
    // You are trying to find a single user, so set the controls to return only on instance 
    SearchControls contr = new SearchControls(); 
    contr.setCountLimit(1L); 
    try 
    { 
    NamingEnumeration<SearchResult> results = ctx.search(userContext, filter, contr); 
    while (results.hasMore()) 
    { 
     // User found 
     SearchResult user = results.next(); 
    } else { 
     // No user found 
    } 
    } catch (NamingException e) { 
     // If there is more than one result, this error will be thrown from the while loop 
    } 
}