Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Ошибка при подключении к LDAP серверу?


Автор: JulT 19.5.2006, 12:18
На одном из форумов,мой брат задал вопрос, но так и не получил на него ответа, может тут чем помогут.ХЭЛП
Вопрос:
Код

Проблема в следующем, пытаюсь подконектиться к LDAP серверу,
пишу следующее:
env[i].put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env[i].put(Context.PROVIDER_URL, "ldap://10.100.100.11:389/dc=mtu,dc=loc");
env[i].put(Context.SECURITY_PRINCIPAL, "cn=JulT,ou=UkrService,dc=mtu,dc=loc");
env[i].put(Context.SECURITY_CREDENTIALS, "xxxx");
В результате получаю:
javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C09030B, comment: AcceptSecurityContext error, data 525, v893
Вычитал на одном форуме, что такая ошибка вылетает в случае если: 
This error is caused by the wrong setting of
   java.naming.security.principal.Расшифровка:
javax.naming.AuthenticationException: 
   [LDAP: error code 49 - 80090308: LdapErr: DSID-0C09030B, comment: 
     AcceptSecurityContext error, data 525, v893 ]
     A: This error is caused by the wrong setting of
     java.naming.security.principal.
   A full DN must be used here, something like:
   CN=FName LName,OU=OrgUnit_the_user_stored_in,DC=Domain_name,DC=Domain_suffix
Но у меня же все вроде правильно с синтаксисом, юзер такой есть сто пудов.
Прошу подсказать в чем проблема.
 

Автор: JulT 19.5.2006, 16:53
вопрос снят, спасибо 

Автор: jxr 5.1.2009, 20:48
Код

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ldapapp2;

import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
import java.util.*;


public class Main {

    /**
     * @param args the command line arguments
     */

/**
 * Demonstrates how to create an initial context to an LDAP server
 * using simple authentication.
 */

        public static void main(String[] args) {

            Hashtable authEnv = new Hashtable(99);
            String userName = "cсnasirov";
            String passWord = "12345";
            String base = "ou=People,dc=mydomain,dc=com";
            String dn = "uid=" + userName + "," + base;

            String ldapURL = "ldap://192.168.0.99:389/";
            ldapURL += base;

            authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            authEnv.put(Context.PROVIDER_URL, ldapURL);
            authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            authEnv.put(Context.SECURITY_PRINCIPAL, userName);
            authEnv.put(Context.SECURITY_CREDENTIALS, passWord);

            try {
                DirContext authContext = new InitialDirContext(authEnv);
                System.out.println("Authentication Success!");
            }

            catch (AuthenticationException authEx)
            {
                System.out.println("Authentication failed!");
            }
            catch (NamingException namEx) {
                System.out.println("Something went wrong!");
                namEx.printStackTrace();
            }
        }
}



Этот код не работаеть? Эксепшин!
Код

avax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 525, vece
        at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3005)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2951)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2753)
        at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2667)
        at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:287)
        at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
        at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
        at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
        at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
        at javax.naming.InitialContext.init(InitialContext.java:223)
        at javax.naming.InitialContext.<init>(InitialContext.java:197)
        at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:82)
        at ldapapp2.LDAPAuthentication.authenticateUser(LDAPAuthentication.java:89)
        at ldapapp2.Main.main(Main.java:31)


"ou=Users" тоже попробывал... тоже не работало!

Автор: jxr 6.1.2009, 09:32
???

Автор: jxr 6.1.2009, 13:27
Знаю, LDAP не просто...
Ни кто не хочеть помочь мне.... smile 

Автор: VSergeyV 8.1.2009, 09:42
Цитата(jxr @  6.1.2009,  13:27 Найти цитируемый пост)
Знаю, LDAP не просто...

У меня в первый раз без проблем все получилось, подключался к Active Directory, правда писал на Groovy smile 
Для того чтобы не гадать с параметрами подключения и поиска использовал Win32 тулзу Softerra LDAP Administrator, попробуйте сначала войти через нее

может поможет
Код

        def appConfig = grailsApplication.config
        def ldapUrls = appConfig.ldap.server.url ?: [ "ldap://localhost:389/" ]
        def searchBase = appConfig.ldap.search.base ?: ""
        def searchUser = appConfig.ldap.search.user ?: ""
        def searchPassword = appConfig.ldap.search.pass ?: ""

        // Accept strings and GStrings for convenience, but convert to
        // a list.
        if (ldapUrls && !(ldapUrls instanceof Collection)) {
            ldapUrls = [ ldapUrls ]
        }

        // Set up the configuration for the LDAP search we are about
        // to do.
        def env = new Hashtable()
        env[Context.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.ldap.LdapCtxFactory"
        if (searchUser) {
            // Non-anonymous access for the search.
            env[Context.SECURITY_AUTHENTICATION] = "simple"
            env[Context.SECURITY_PRINCIPAL] = searchUser
            env[Context.SECURITY_CREDENTIALS] = searchPassword
        }

        // Find an LDAP server that we can connect to.
        def ctx
        def urlUsed = ldapUrls.find { url ->
            env[Context.PROVIDER_URL] = url
            // If an exception occurs, log it.
            try {
                ctx = new InitialDirContext(env)
                return true
            }
            catch (NamingException e) {
                return false
            }
        }

        if (!urlUsed) {
            def msg = 'No LDAP server available.'
            throw new org.jsecurity.authc.AuthenticationException(msg)
        }

        // Look up the DN for the LDAP entry that has a 'uid' value
        // matching the given username.
        def matchAttrs = new BasicAttributes(true)

        def result = ctx.search(searchBase, matchAttrs)
        result.each {
          ....
        }



Код

ldap {
    server.url="ldap://XXX.XXX.XXX.XXX:XXX/"
    search.base="CN=Users,DC=domain,DC=domain,DC=com"
    search.user="******@domain.domain.com"
    search.pass="*******"
}



Автор: Krivoy 11.1.2009, 13:20
Сорри может за не правильное направление(c доменами, а тем более с win не работал), но ->

Вы уверены что юзернаме для коннекта к LDAP должен быть такой??? ->
Цитата

String userName = "cсnasirov";

 Там оно вроде как ругалось именно в этом направлении -
Цитата

   A full DN must be used here, something like:
   CN=FName LName,OU=OrgUnit_the_user_stored_in,DC=Domain_name,DC=Domain_suffix

Ещё раз извиняюсь - не знаю где он в виндовом домене, но у меня юзер для коннекта типа
"cn=admin,dc=domen"

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)