com.unboundid.ldap.sdk.LDAPConnection类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(16.7k)|赞(0)|评价(0)|浏览(175)

本文整理了Java中com.unboundid.ldap.sdk.LDAPConnection类的一些代码示例,展示了LDAPConnection类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。LDAPConnection类的具体详情如下:
包路径:com.unboundid.ldap.sdk.LDAPConnection
类名称:LDAPConnection

LDAPConnection介绍

[英]This class provides a facility for interacting with an LDAPv3 directory server. It provides a means of establishing a connection to the server, sending requests, and reading responses. See RFC 4511 for the LDAPv3 protocol specification and more information about the types of operations defined in LDAP.

Creating, Establishing, and Authenticating Connections An LDAP connection can be established either at the time that the object is created or as a separate step. Similarly, authentication can be performed on the connection at the time it is created, at the time it is established, or as a separate process. For example:

// Create a new, unestablished connection.  Then connect and perform a 
// simple bind as separate operations. 
LDAPConnection c = new LDAPConnection(); 
c.connect(address, port); 
BindResult bindResult = c.bind(bindDN, password); 
// Create a new connection that is established at creation time, and then 
// authenticate separately using simple authentication. 
LDAPConnection c = new LDAPConnection(address, port); 
BindResult bindResult = c.bind(bindDN, password); 
// Create a new connection that is established and bound using simple 
// authentication all in one step. 
LDAPConnection c = new LDAPConnection(address, port, bindDN, password);

When authentication is performed at the time that the connection is established, it is only possible to perform a simple bind and it is not possible to include controls in the bind request, nor is it possible to receive response controls if the bind was successful. Therefore, it is recommended that authentication be performed as a separate step if the server may return response controls even in the event of a successful authentication (e.g., a control that may indicate that the user's password will soon expire). See the BindRequest class for more information about authentication in the UnboundID LDAP SDK for Java.

By default, connections will use standard unencrypted network sockets. However, it may be desirable to create connections that use SSL/TLS to encrypt communication. This can be done by specifying a javax.net.SocketFactory that should be used to create the socket to use to communicate with the directory server. The javax.net.ssl.SSLSocketFactory#getDefault method or the javax.net.ssl.SSLContext#getSocketFactory method may be used to obtain a socket factory for performing SSL communication. See the JSSE Reference Guide for more information on using these classes. Alternately, you may use the com.unboundid.util.ssl.SSLUtil class to simplify the process.

Whenever the connection is no longer needed, it may be terminated using the LDAPConnection#close method.

Processing LDAP Operations This class provides a number of methods for processing the different types of operations. The types of operations that can be processed include:

  • Abandon -- This may be used to request that the server stop processing on an operation that has been invoked asynchronously.
  • Add -- This may be used to add a new entry to the directory server. See the AddRequest class for more information about processing add operations.
  • Bind -- This may be used to authenticate to the directory server. See the BindRequest class for more information about processing bind operations.
  • Compare -- This may be used to determine whether a specified entry has a given attribute value. See the CompareRequest class for more information about processing compare operations.
  • Delete -- This may be used to remove an entry from the directory server. See the DeleteRequest class for more information about processing delete operations.
  • Extended -- This may be used to process an operation which is not part of the core LDAP protocol but is a custom extension supported by the directory server. See the ExtendedRequest class for more information about processing extended operations.
  • Modify -- This may be used to alter an entry in the directory server. See the ModifyRequest class for more information about processing modify operations.
  • Modify DN -- This may be used to rename an entry or subtree and/or move that entry or subtree below a new parent in the directory server. See the ModifyDNRequest class for more information about processing modify DN operations.
  • Search -- This may be used to retrieve a set of entries in the server that match a given set of criteria. See the SearchRequestclass for more information about processing search operations.

Most of the methods in this class used to process operations operate in a synchronous manner. In these cases, the SDK will send a request to the server and wait for a response to arrive before returning to the caller. In these cases, the value returned will include the contents of that response, including the result code, diagnostic message, matched DN, referral URLs, and any controls that may have been included. However, it also possible to process operations asynchronously, in which case the SDK will return control back to the caller after the request has been sent to the server but before the response has been received. In this case, the SDK will return an AsyncRequestID object which may be used to later abandon or cancel that operation if necessary, and will notify the client when the response arrives via a listener interface.

This class is mostly threadsafe. It is possible to process multiple concurrent operations over the same connection as long as the methods being invoked will not change the state of the connection in a way that might impact other operations in progress in unexpected ways. In particular, the following should not be attempted while any other operations may be in progress on this connection:

  • Using one of the connect methods to re-establish the connection.
  • Using one of the close methods to terminate the connection.
  • Using one of the bind methods to attempt to authenticate the connection (unless you are certain that the bind will not impact the identity of the associated connection, for example by including the retain identity request control in the bind request if using the Commercial Edition of the LDAP SDK in conjunction with a Ping Identity, UnboundID, or Alcatel-Lucent 8661 Directory Server).
  • Attempting to make a change to the way that the underlying communication is processed (e.g., by using the StartTLS extended operation to convert an insecure connection into a secure one).
    [中]此类提供了与LDAPv3目录服务器交互的工具。它提供了一种与服务器建立连接、发送请求和读取响应的方法。有关LDAPv3协议规范和LDAP中定义的操作类型的更多信息,请参见{$0$}。
    创建、建立和验证连接LDAP连接可以在创建对象时建立,也可以作为单独的步骤建立。类似地,可以在创建连接时、建立连接时或作为单独的过程对连接执行身份验证。例如:
// Create a new, unestablished connection.  Then connect and perform a 
// simple bind as separate operations. 
LDAPConnection c = new LDAPConnection(); 
c.connect(address, port); 
BindResult bindResult = c.bind(bindDN, password); 
// Create a new connection that is established at creation time, and then 
// authenticate separately using simple authentication. 
LDAPConnection c = new LDAPConnection(address, port); 
BindResult bindResult = c.bind(bindDN, password); 
// Create a new connection that is established and bound using simple 
// authentication all in one step. 
LDAPConnection c = new LDAPConnection(address, port, bindDN, password);

当在建立连接时执行身份验证时,只可能执行简单绑定,不可能在绑定请求中包含控件,如果绑定成功,也不可能接收响应控件。因此,如果服务器即使在认证成功的情况下也可能返回响应控件(例如,可能指示用户密码即将过期的控件),则建议将认证作为单独的步骤执行。有关未绑定LDAP SDK for Java中身份验证的更多信息,请参阅BindRequest类。
默认情况下,连接将使用标准的未加密网络套接字。但是,可能需要创建使用SSL/TLS加密通信的连接。这可以通过指定javax来实现。网SocketFactory,用于创建用于与目录服务器通信的套接字。javax。网ssl。SSLSocketFactory#getDefault方法或javax。网ssl。SSLContext#getSocketFactory方法可用于获取用于执行SSL通信的套接字工厂。有关使用这些类的更多信息,请参见{$1$}。或者,您可以使用com。无限的。util。ssl。SSLUtil类简化了该过程。
当不再需要连接时,可以使用LDAPConnection#close方法终止连接。
处理LDAP操作此类提供了许多方法来处理不同类型的操作。可以处理的操作类型包括:
*放弃——这可用于请求服务器停止处理已异步调用的操作。
*Add——这可用于向目录服务器添加新条目。有关处理添加操作的更多信息,请参阅AddRequest类。
*绑定——这可用于向目录服务器进行身份验证。有关处理绑定操作的更多信息,请参见BindRequest类。
*比较——这可用于确定指定项是否具有给定的属性值。有关处理比较操作的更多信息,请参见CompareRequest类。
*Delete——这可用于从目录服务器中删除条目。有关处理删除操作的更多信息,请参阅DeleteRequest类。
*Extended——这可用于处理不属于核心LDAP协议的操作,但它是目录服务器支持的自定义扩展。有关处理扩展操作的更多信息,请参阅ExtendedRequest类。
*Modify——这可用于更改目录服务器中的条目。有关处理修改操作的更多信息,请参见ModifyRequest类。
*Modify DN——这可用于重命名目录服务器中的条目或子树和/或将该条目或子树移动到新父目录下。有关处理修改DN操作的更多信息,请参阅ModifyDNRequest类。
*搜索——这可用于检索服务器中与给定条件集匹配的一组条目。有关处理搜索操作的更多信息,请参阅SearchRequestclass。
此类中用于处理操作的大多数方法以同步方式运行。在这些情况下,SDK将向服务器发送请求,并等待响应到达后再返回调用方。在这些情况下,返回的值将包括该响应的内容,包括结果代码、诊断消息、匹配的DN、引用URL以及可能包含的任何控件。但是,也可以异步处理操作,在这种情况下,SDK将在请求发送到服务器之后但在收到响应之前将控制权返回给调用方。在这种情况下,SDK将返回一个AsyncRequestID对象,该对象可用于以后在必要时放弃或取消该操作,并在响应通过侦听器接口到达时通知客户端。
这个类主要是线程安全的。只要所调用的方法不会以可能以意外方式影响正在进行的其他操作的方式更改连接状态,就可以在同一连接上处理多个并发操作。特别是,在对该连接进行任何其他操作时,不应尝试以下操作:
*使用连接方法之一重新建立连接。
*使用关闭方法之一终止连接。
*使用bind方法之一尝试验证连接(除非您确定绑定不会影响关联连接的标识,例如,如果将LDAP SDK的商业版与Ping标识、Unbounded或Alcatel-Lucent 8661目录服务器结合使用,则在绑定请求中包含保留标识请求控件)。
*试图更改底层通信的处理方式(例如,通过使用StartTLS扩展操作将不安全连接转换为安全连接)。

代码示例

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

/**
 * Unbinds and disconnects from the directory server.
 *
 * @throws  LDAPException  If a problem occurs.
 */
public void disconnect()
    throws LDAPException
{
 authDN = null;
 authPW = null;
 conn.close();
 if (socketFactory == null)
 {
  conn = new com.unboundid.ldap.sdk.LDAPConnection();
 }
 else
 {
  conn = new com.unboundid.ldap.sdk.LDAPConnection(
     new LDAPToJavaSocketFactory(socketFactory));
 }
}

代码示例来源:origin: otto-de/edison-microservice

boolean authenticate(final LDAPConnection ldap, final String userDN, final String password) throws LDAPException {
    final BindResult bindResult = ldap.bind(userDN, password);
    if (bindResult.getResultCode().equals(ResultCode.SUCCESS)) {
      LOG.debug("Login successful: " + userDN); // don't expose user names at successful login as this is a security issue
      return true;
    } else {
      LOG.warn("Access denied: " + userDN);
      return false;
    }
  }
}

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-minimal-edition

throws LDAPSearchException
return search((SearchRequest) searchRequest);

代码示例来源:origin: tmobile/pacbot

/**
 * fall back to connect using IP itself
 * @return
 */
private LDAPConnection tryGettingConnectionWithDirectIP() throws LDAPException {
  LDAPConnection ldapConnection = new LDAPConnection();
  try{
  hostIps.forEach(
        ip->{
          try{
              ldapConnection.connect(ip, ntPort,connectTimeout);
              throw new BreakLoopException();
          }catch(LDAPException exception){
            log.debug("unable to connect using" + ip + ", trying next ip");
          }
        }
      );
  }catch(BreakLoopException br){
    log.info("got connected using IP");
  }
  if(ldapConnection.isConnected())
    return ldapConnection;
  else{
    throw new LDAPException(ResultCode.CONNECT_ERROR,"unable to connect using IP");
  }
}

代码示例来源:origin: apiman/apiman

private static LDAPConnection getConnection(Map<LdapConfigBean, LDAPConnectionPool> map,
    SSLSocketFactory socketFactory, LdapConfigBean config) throws LDAPException {
  if (!map.containsKey(config)) {
    LDAPConnection template = new LDAPConnection(config.getHost(), config.getPort());
    if (socketFactory != null)
      template.setSocketFactory(socketFactory);
    map.put(config, new LDAPConnectionPool(template, MAX_CONNECTIONS_PER_POOL));
  }
  return map.get(config).getConnection();
}

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-minimal-edition

final LDAPConnection conn = new LDAPConnection(connection.socketFactory,
   connection.connectionOptions, host, port);
     conn.processExtendedOperation(connStartTLSRequest);
  if (startTLSResult.getResultCode() != ResultCode.SUCCESS)
  conn.setDisconnectInfo(DisconnectType.SECURITY_PROBLEM, null, le);
  conn.close();
  conn.bind(bindRequest);
  conn.setDisconnectInfo(DisconnectType.BIND_FAILED, null, le);
  conn.close();

代码示例来源:origin: org.geomajas.plugin/geomajas-plugin-staticsecurity-ldap

protected SearchResult execute(SearchRequest request, String bindDN, String password) {
  LDAPConnection connection = null;
  try {
    if (allowAllSocketFactory) {
      SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
      connection = new LDAPConnection(sslUtil.createSSLSocketFactory(), serverHost, serverPort);
    } else {
      connection = new LDAPConnection(serverHost, serverPort);
    }
    if (bindDN != null) {
      BindResult auth = connection.bind(bindDN, password);
      if (!auth.getResultCode().isConnectionUsable()) {
        log.error("Connection not usable, result code : " + auth.getResultCode());
      }
    }
    return connection.search(request);
  } catch (LDAPException le) {
    String message = le.getMessage();
    if (!message.startsWith("Unable to bind as user ")) {
      log.error(le.getMessage(), le);
    }
  } catch (GeneralSecurityException gse) {
    log.error(gse.getMessage(), gse);
  } finally {
    if (null != connection) {
      connection.close();
    }
  }
  return null;
}

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

if (! conn.isConnected())
for (int i=0; i < addresses.length; i++)
 if (addresses[i].equals(conn.getConnectedAddress()) &&
   (ports[i] == conn.getConnectedPort()))
  final LDAPConnection conn = new LDAPConnection(socketFactory,
     connectionOptions, p.getFirst(), p.getSecond());
  if (healthCheck != null)
    conn.close();
    throw le;

代码示例来源:origin: io.vertx/vertx-auth-service

private void insertTestUsers() throws LDAPException {
 LDAPConnection connection = null;
 try {
  connection = new LDAPConnection("localhost", 10389);
  // entry tim/sausages
  List<Attribute> addRequest = new ArrayList<Attribute>();
  addRequest.add(new Attribute("objectClass", "top"));
  addRequest.add(new Attribute("objectClass", "person"));
  addRequest.add(new Attribute("objectClass", "organizationalPerson"));
  addRequest.add(new Attribute("objectClass", "inetOrgPerson"));
  addRequest.add(new Attribute("cn", "Tim Fox"));
  addRequest.add(new Attribute("sn", "Fox"));
  addRequest.add(new Attribute("mail", "tim@example.com"));
  addRequest.add(new Attribute("uid", "tim"));
  addRequest.add(new Attribute("userPassword", "{ssha}d0M5Z2qjOOCSCQInvZHgVAleCqU5I+ag9ZHXMw=="));
  connection.add("uid=tim,ou=users,dc=foo,dc=com", addRequest);
 } finally {
  if (connection != null) {
   connection.close();
  }
 }
}

代码示例来源:origin: gsvigruha/cosyan

public AuthToken auth(String username, String password, String token) throws AuthException {
  String ldapHost = config.get(Config.LDAP_HOST);
  try {
   LDAPConnection connection = new LDAPConnection(
     ldapHost,
     Integer.valueOf(config.get(Config.LDAP_PORT)),
     username + "@" + ldapHost,
     password);

   if (connection.isConnected()) {
    return new LDAPToken(connection, username, token);
   } else {
    connection.close();
    throw new AuthException("Connection not connected.");
   }
  } catch (LDAPException e) {
   throw new AuthException(e.getExceptionMessage());
  }
 }
}

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

new LDAPConnection(socketFactory, connectionOptions);
for (final InetAddress a : orderAddresses(resolveHostname()))
 try
  conn.connect(hostname, a, port,
     connectionOptions.getConnectTimeoutMillis());
  if (healthCheck != null)
   conn.close();

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

/**
 * Creates a new LDAP connection based on the JSON specification.  The
 * connection will be authenticated if appropriate.
 *
 * @return  The LDAP connection that was created.
 *
 * @throws  LDAPException  If a problem is encountered while trying to
 *                         establish or authenticate the connection.
 */
public LDAPConnection createConnection()
    throws LDAPException
{
 final LDAPConnection connection = createUnauthenticatedConnection();
 if (bindRequest != null)
 {
  try
  {
   connection.bind(bindRequest);
  }
  catch (final LDAPException le)
  {
   Debug.debugException(le);
   connection.close();
   throw le;
  }
 }
 return connection;
}

代码示例来源:origin: tmobile/pacbot

/**
 * 
 * @param ldapConnection
 */
private void closeConnection(LDAPConnection ldapConnection) {
  if (ldapConnection != null) {
    ldapConnection.close();
  }
}

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-minimal-edition

startTLSRequest = null;
if (isConnected())
 setDisconnectInfo(DisconnectType.RECONNECT, null, null);
 close();
 setDisconnectInfo(DisconnectType.LOCAL_ERROR, null, e);
 connectionInternals = null;
 throw new LDAPException(ResultCode.CONNECT_ERROR,
    ERR_CONN_CONNECT_ERROR.get(getHostPort(), String.valueOf(e)), e);
  cachedSchema = getCachedSchema(this);

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

/**
 * {@inheritDoc}
 */
@Override()
public LDAPConnection getConnection()
    throws LDAPException
{
 return new LDAPConnection(socketFactory, connectionOptions, address, port);
}

代码示例来源:origin: org.esbtools.auth/cert-ldap-login-module-common

BindResult bindResult = null;
if (!ldapConnection.isConnected()) {
  ldapConnection.connect(
    ldapConfiguration.getServer(), ldapConfiguration.getPort());
  bindResult = ldapConnection.bind(
    ldapConfiguration.getBindDn(), ldapConfiguration.getBindDNPwd());
} else if (ldapConnection.getLastBindRequest() == null) {
  bindResult = ldapConnection.bind(
    ldapConfiguration.getBindDn(), ldapConfiguration.getBindDNPwd());

代码示例来源:origin: com.nimbusds/common

extResult = con.processExtendedOperation(extRequest);
con.close();
con.close();

代码示例来源:origin: com.unboundid/unboundid-ldapsdk-commercial-edition

Collections.unmodifiableSet(EnumSet.noneOf(OperationType.class)));
if (! connection.isConnected())
serverSet = new SingleServerSet(connection.getConnectedAddress(),
                connection.getConnectedPort(),
                connection.getLastUsedSocketFactory(),
                connection.getConnectionOptions());
bindRequest = connection.getLastBindRequest();
healthCheckThread.start();
final LDAPConnectionOptions opts = connection.getConnectionOptions();
if (opts.usePooledSchema())
  final Schema schema = connection.getSchema();
  if (schema != null)
   connection.setCachedSchema(schema);

代码示例来源:origin: otto-de/edison-microservice

public LDAPConnection buildLdapConnection() throws GeneralSecurityException, LDAPException {
  final LDAPConnection ldapConnection = new LDAPConnection(ldapProperties.getHost(), ldapProperties.getPort());
  ldapConnection.processExtendedOperation(new StartTLSExtendedRequest(SSL_UTIL.createSSLContext()));
  return ldapConnection;
}

代码示例来源:origin: tmobile/pacbot

numberOfTries++;
    log.debug(String.format("trial number -> %s" , numberOfTries));
    ldapConnection = new LDAPConnection(connectionOptions);
    ldapConnection.connect(ntDomain, ntPort,connectTimeout);
    break;
}catch(LDAPException exception) {

相关文章

LDAPConnection类方法