Java 使用IP地址属性的LDAP查询
我正在寻找一种使用用户的IP地址查询LDAP的方法 当有人使用浏览器时,浏览器会发送其IP地址。 我想使用该IP地址查询LDAP以查找该IP地址所属的用户名Java 使用IP地址属性的LDAP查询,java,active-directory,ldap,Java,Active Directory,Ldap,我正在寻找一种使用用户的IP地址查询LDAP的方法 当有人使用浏览器时,浏览器会发送其IP地址。 我想使用该IP地址查询LDAP以查找该IP地址所属的用户名 我已经设法用Java中的LDAP连接到AD。请阅读EJP的评论,并首先重新考虑您的要求 无论您为什么希望这样做,您都需要采取以下两个步骤: 查找用户所在的上下文(LDAP容器)。广告默认值为cn=Users,dc=your,dc=domain,dc=com 识别包含IP地址的LDAP属性(现在假设networkAddress) 从HTTP
我已经设法用Java中的LDAP连接到AD。请阅读EJP的评论,并首先重新考虑您的要求 无论您为什么希望这样做,您都需要采取以下两个步骤:
- 查找用户所在的上下文(LDAP容器)。广告默认值为
cn=Users,dc=your,dc=domain,dc=com
- 识别包含IP地址的LDAP属性(现在假设
)networkAddress
- 从HTTP请求中检索IP地址(比如
)stringuseraddress
- 使用过滤器
(&(objectClass=inetOrgPerson)(networkAddress=userAddress))执行(用户)对象的查询
LdapConnection
对象):
public void getUserByIp(LdapContext ctx,字符串userAddress)
{
//替换为您的上下文和域名
String userContext=“cn=Users,dc=your,dc=domain,dc=com”;
字符串筛选器=“(&(objectClass=inetOrgPerson)(networkAddress=“+userAddress+”)”);
//您正在尝试查找单个用户,因此请将控件设置为仅在实例上返回
SearchControls Control=新的SearchControls();
控制设置计数限值(1L);
尝试
{
NamingEnumeration results=ctx.search(userContext、filter、contr);
while(results.hasMore())
{
//用户发现
SearchResult user=results.next();
}否则{
//找不到用户
}
}捕获(NamingE例外){
//如果有多个结果,则会从while循环中抛出此错误
}
}
奇怪的要求。用户只能从一个IP地址登录?你在目录中有用户的IP地址吗?如果是,在什么属性中?请注意,浏览器不会发送其IP地址,但服务器会在每次请求时记录远程客户端IP。这不是很可靠:思考(反向)代理、NAT等。
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
}
}