Java and ldap example

Modes of Authenticating to LDAP

In the LDAP, authentication information is supplied in the «bind» operation. In LDAP v2, a client initiates a connection with the LDAP server by sending the server a «bind» operation that contains the authentication information.

In the LDAP v3, this operation serves the same purpose, but it is optional. A client that sends an LDAP request without doing a «bind» is treated as an anonymous client (see the Anonymous section for details). In the LDAP v3, the «bind» operation may be sent at any time, possibly more than once, during the connection. A client can send a «bind» request in the middle of a connection to change its identity. If the request is successful, then all outstanding requests that use the old identity on the connection are discarded and the connection is associated with the new identity.

The authentication information supplied in the «bind» operation depends on the authentication mechanism that the client chooses. See Authentication Mechanisms for a discussion of the authentication mechanism.

Authenticating to the LDAP by Using the JNDI

In the JNDI, authentication information is specified in environment properties. When you create an initial context by using the InitialDirContext class (or its superclass or subclass), you supply a set of environment properties, some of which might contain authentication information. You can use the following environment properties to specify the authentication information.

  • Context.SECURITY_AUTHENTICATION ("java.naming.security.authentication").
    Specifies the authentication mechanism to use. For the LDAP service provider in the JDK, this can be one of the following strings: "none", "simple", sasl_mech, where sasl_mech is a space-separated list of SASL mechanism names. See the Authentication Mechanisms for a description of these strings.
  • Context.SECURITY_PRINCIPAL ("java.naming.security.principal").
    Specifies the name of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.
  • Context.SECURITY_CREDENTIALS ("java.naming.security.credentials").
    Specifies the credentials of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.

When the initial context is created, the underlying LDAP service provider extracts the authentication information from these environment properties and uses the LDAP «bind» operation to pass them to the server.

Читайте также:  Java file list all files in directory

The following example shows how, by using a simple clear-text password, a client authenticates to an LDAP server.

// Set up the environment for creating the initial context Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Authenticate as S. User and password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret"); // Create the initial context DirContext ctx = new InitialDirContext(env); // . do something useful with ctx

Using Different Authentication Information for a Context

If you want to use different authentication information for an existing context, then you can use Context.addToEnvironment() and Context.removeFromEnvironment() to update the environment properties that contain the authentication information. Subsequent invocations of methods on the context will use the new authentication information to communicate with the server.

The following example shows how the authentication information of a context is changed to "none" after the context has been created.

// Authenticate as S. User and the password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret"); // Create the initial context DirContext ctx = new InitialDirContext(env); // . do something useful with ctx // Change to using no authentication ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none"); // . do something useful with ctx

Authentication Failures

Authentication can fail for a number of reasons. For example, if you supply incorrect authentication information, such as an incorrect password or principal name, then an AuthenticationException is thrown.

Here is an example that is a variation of the previous example. This time, an incorrect password causes the authentication to fail.

// Authenticate as S. User and give an incorrect password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "notmysecret");

This produces the following output.

javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials] .

Because different servers support different authentication mechanisms, you might request an authentication mechanism that the server does not support. In this case, an AuthenticationNotSupportedException will be thrown.

Here is an example that is a variation of the previous example. This time, an unsupported authentication mechanism ("custom") causes the authentication to fail.

// Authenticate as S. User and the password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "custom"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret");

This produces the following output.

javax.naming.AuthenticationNotSupportedException: custom .

Источник

Java and ldap example

In the LDAP, authentication information is supplied in the «bind» operation. In LDAP v2, a client initiates a connection with the LDAP server by sending the server a «bind» operation that contains the authentication information.

In the LDAP v3, this operation serves the same purpose, but it is optional. A client that sends an LDAP request without doing a «bind» is treated as an anonymous client (see the Anonymous Authentication section for details). In the LDAP v3, the «bind» operation may be sent at any time, possibly more than once, during the connection. A client can send a «bind» request in the middle of a connection to change its identity. If the request is successful, then all outstanding requests that use the old identity on the connection are discarded and the connection is associated with the new identity.

Читайте также:  Php output json format

The authentication information supplied in the «bind» operation depends on the authentication mechanism that the client chooses. See the next section for a discussion of the authentication mechanism.

Authenticating to the LDAP by Using the JNDI

  • Context.SECURITY_AUTHENTICATION ("java.naming.security.authentication").
    Specifies the authentication mechanism to use. For the Sun LDAP service provider, this can be one of the following strings: "none", "simple", sasl_mech, where sasl_mech is a space-separated list of SASL mechanism names. See the next section for a description of these strings.
  • Context.SECURITY_PRINCIPAL ("java.naming.security.principal").
    Specifies the name of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.
  • Context.SECURITY_CREDENTIALS ("java.naming.security.credentials").
    Specifies the credentials of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.
// Set up the environment for creating the initial context Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Authenticate as S. User and password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret"); // Create the initial context DirContext ctx = new InitialDirContext(env); // . do something useful with ctx 

Using Different Authentication Information for a Context

If you want to use different authentication information for an existing context, then you can use Context.addToEnvironment() and Context.removeFromEnvironment() to update the environment properties that contain the authentication information. Subsequent invocations of methods on the context will use the new authentication information to communicate with the server.

The following example shows how the authentication information of a context is changed to "none" after the context has been created.

// Authenticate as S. User and the password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret"); // Create the initial context DirContext ctx = new InitialDirContext(env); // . do something useful with ctx // Change to using no authentication ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none"); // . do something useful with ctx

Authentication Failures

Authentication can fail for a number of reasons. For example, if you supply incorrect authentication information, such as an incorrect password or principal name, then an AuthenticationException is thrown.

Here’s an example that is a variation of the previous example. This time, an incorrect password causes the authentication to fail.

// Authenticate as S. User and give an incorrect password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "notmysecret");
javax.naming.AuthenticationException: [LDAP: Invalid Credentials] at java.lang.Throwable.(Compiled Code) at java.lang.Exception.(Compiled Code) .

Because different servers support different authentication mechanisms, you might request an authentication mechanism that the server does not support. In this case, an AuthenticationNotSupportedException will be thrown.

Читайте также:  Css before content link

Here’s an example that is a variation of the previous example. This time, an unsupported authentication mechanism ("custom") causes the authentication to fail.

// Authenticate as S. User and the password "mysecret" env.put(Context.SECURITY_AUTHENTICATION, "custom"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "mysecret");
javax.naming.AuthenticationNotSupportedException: Unsupported value for java.naming.security.authentication property. at java.lang.Throwable.(Compiled Code) at java.lang.Exception.(Compiled Code) at javax.naming.NamingException.(Compiled Code) .

Источник

Учебник по Java для LDAP (включая инструкции по установке сервера / клиента LDAP)

Из этого туториала вы узнаете, как написать код Java для взаимодействия с LDAP. Но прежде чем мы сможем это сделать, нам нужно будет настроить сервер и клиент LDAP на нашей машине.

Если в данный момент вы не уверены точно, что такое LDAP, я рекомендую этот пост, в котором содержится отличное определение с примерами. (В двух словах это помогает думать о сервере LDAP как о специализированной базе данных).

Установка сервера LDAP

Я бегу на MBP. Посмотрев некоторое время, я обнаружил, что самым простым для установки LDAP-сервером был ApacheDirectory, который вы можете скачать здесь . (Установка и запуск сервера должны занять не более 5 минут)

После установки он автоматически запускает демон. Затем вы можете запустить сервер с помощью этой команды.

Для дальнейших инструкций по установке смотрите здесь .

Клиент LDAP

Вы захотите просмотреть содержимое вашего сервера LDAP. Простейший LDAP-клиент для установки – это Apache Directory Studio, который можно скачать здесь .

После того, как он загружен, вам необходимо создать соединение с сервером – инструкции для которого содержатся здесь .

При подключении ваша Apache Directory Studio должна выглядеть примерно так:

Снимок экрана 2015-09-24 в 13.20.17

Теперь для доступа к LDAP из Java-программы. Лучший способ показать вам, как это сделать, – через пример программы. Программа выполнит следующие задачи:

  • Создать новый объект LDAP
  • Просмотр объекта LDAP
  • Добавить новый атрибут в объект LDAP
  • Изменить атрибут в объекте LDAP
  • Удалить атрибут в объекте LDAP
  • Удалить объект LDAP

Примечание. Этот класс очищается после себя, т. Е. Он оставляет сервер LDAP в состоянии, в котором он был найден. Если вы хотите увидеть различные задачи в действии, просто запустите одну из задач и посмотрите на объект LDAP через клиент LDAP. Не забудьте, что вы можете изменить объект в клиенте LDAP и протестировать его таким образом.

Источник

Оцените статью