Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / ldap: connection from spring project / 10 сообщений из 10, страница 1 из 1
06.06.2016, 18:37
    #39251467
kadet
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
всем привет,
коллеги, я уже "запарился". Читаю доку и пытаюсь научится работать с ldap из spring.

У меня не получается подключится к серверу на локальном хосте. все время вываливается ошибка LDAP: error code 49 - Invalid Credentials
Код: java
1.
2.
3.
4.
5.
[DEBUG] [http-bio-8080-exec-8 05:09:57] (BindAuthenticator.java:bindWithDn:108) Attempting to bind as uid=admin,ou=people,dc=springframework,dc=org
[DEBUG] [http-bio-8080-exec-8 05:09:57] (DefaultSpringSecurityContextSource.java:setupEnvironment:73) Removing pooling flag for user uid=admin,ou=people,dc=springframework,dc=org
[DEBUG] [http-bio-8080-exec-8 05:09:57] (BindAuthenticator.java:handleBindException:150) Failed to bind as uid=admin,ou=people: org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
[TRACE] [http-bio-8080-exec-8 05:09:57] (AbstractApplicationContext.java:publishEvent:301) Publishing event in Root WebApplicationContext: org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent[source=org.springframework.security.authentication.UsernamePasswordAuthenticationToken@cc7d4de0: Principal: admin; Credentials: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 280B88E83FBFFD314B12F4AB65E40E92; Not granted any authorities]
[DEBUG] [http-bio-8080-exec-8 05:09:57] (AbstractAuthenticationProcessingFilter.java:unsuccessfulAuthentication:318) Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials



так выглядит мой файл конфигураций:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
	<security:http auto-config="true" use-expressions="true" access-denied-page="/krams/auth/denied" >
	
		<security:intercept-url pattern="/krams/auth/login" access="permitAll"/>
		<security:intercept-url pattern="/krams/main/admin" access="hasRole('ROLE_ADMIN')"/>
		<security:intercept-url pattern="/krams/main/common" access="hasRole('ROLE_USER')"/>
		
		<security:form-login
				login-page="/krams/auth/login" 
				authentication-failure-url="/krams/auth/login?error=true" 
				default-target-url="/krams/main/common"/>
			
		<security:logout 
				invalidate-session="true" 
				logout-success-url="/krams/auth/login" 
				logout-url="/krams/auth/logout"/>
	
	</security:http>

	<security:authentication-manager>
	         <security:ldap-authentication-provider user-dn-pattern="uid={0},ou=people"/>
	</security:authentication-manager>
	
	
	<!-- using local server -->
	<security:ldap-server url="ldap://localhost:389/dc=springframework,dc=org" manager-dn="cn=admin" manager-password="secret" />



т.е. я подключаюсь к локальному хосту как "admin" с паролем "secret". Причем я заметил, какой бы пароль не был задан (правильный или не правильный) ошибка одна и таже. Опрос из консоли проходит на "ура":

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
admin@linux:~/Dokumente/howto> ldapsearch -D "cn=admin,dc=springframework,dc=org" -w secret -b "ou=people,dc=springframework,dc=org" -s sub
# extended LDIF
#
# LDAPv3
# base <ou=people,dc=springframework,dc=org> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# people, springframework.org
dn: ou=people,dc=springframework,dc=org
objectClass: organizationalUnit
objectClass: top
ou: people

# muster mustermann + mustermann + mmuster + 123456, people, springframework.
 org
dn: cn=muster mustermann+sn=mustermann+uid=mmuster+userPassword=123456,ou=peop
 le,dc=springframework,dc=org
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
userPassword:: MTIzNDU2
uid: mmuster
sn: mustermann
cn: muster mustermann

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2
admin@linux:~/Dokumente/howto> 


, подключение из Apache directory Studio так же без проблем. Из spring приложения ни в какую не получается.

Я подвесил проект (spring + maven)

подскажите пожалуйста где моя проблема.
...
Рейтинг: 0 / 0
06.06.2016, 18:40
    #39251468
kadet
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
с этим сообщением я подвесил ldif файл
...
Рейтинг: 0 / 0
06.06.2016, 19:00
    #39251483
Blazkowicz
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
kadetAttempting to bind as uid=admin ,ou=people,dc=springframework,dc=org
ldapsearch -D " cn=admin ,dc=springframework,dc=org
...
Рейтинг: 0 / 0
06.06.2016, 19:21
    #39251497
andreykaT
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
когда то я через спринг лдап дружил приложение с актив дайректори. жаль найти не могу - показал бы. вроде все просто. а у тебя какая цель? если как поставщик аккаунтов, и служба активдайректори - то там вообще всего две строчки и "урл" лдап сервера. и все.
...
Рейтинг: 0 / 0
06.06.2016, 19:24
    #39251499
andreykaT
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
    @Bean
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("abc.local", "ldap://192.168.1.1:389");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);


        return provider;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());

    }



и собссно всё. далее, достаешь просто контекст и всё.
...
Рейтинг: 0 / 0
07.06.2016, 11:24
    #39251756
kadet
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
BlazkowiczkadetAttempting to bind as uid=admin ,ou=people,dc=springframework,dc=org
ldapsearch -D " cn=admin ,dc=springframework,dc=org

спасибо,

здесь я пытался подключится как администратор (admin) поэтому лог сбивает с толкую Прошу прощения.
Вот как положено (правильно)
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
[DEBUG] [http-bio-8080-exec-9 09:58:21] (BindAuthenticator.java:bindWithDn:108) Attempting to bind as uid=mmuster,ou=people,dc=springframework,dc=org
[DEBUG] [http-bio-8080-exec-9 09:58:21] (DefaultSpringSecurityContextSource.java:setupEnvironment:73) Removing pooling flag for user uid=mmuster,ou=people,dc=springframework,dc=org
[DEBUG] [http-bio-8080-exec-9 09:58:21] (BindAuthenticator.java:handleBindException:150) Failed to bind as uid=mmuster,ou=people: org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
[TRACE] [http-bio-8080-exec-9 09:58:21] (AbstractApplicationContext.java:publishEvent:301) Publishing event in Root WebApplicationContext: org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent[source=org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ef26a467: Principal: mmuster; Credentials: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffe9938: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A873F995F88F3E1730DD5DD0BD3C5C73; Not granted any authorities]
[DEBUG] [http-bio-8080-exec-9 09:58:21] (AbstractAuthenticationProcessingFilter.java:unsuccessfulAuthentication:318) Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
[DEBUG] [http-bio-8080-exec-9 09:58:21] (AbstractAuthenticationProcessingFilter.java:unsuccessfulAuthentication:319) Updated SecurityContextHolder to contain null Authentication
[DEBUG] [http-bio-8080-exec-9 09:58:21] (AbstractAuthenticationProcessingFilter.java:unsuccessfulAuthentication:320) Delegating to authentication failure handlerorg.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@2a979877
[DEBUG] [http-bio-8080-exec-9 09:58:21] (SimpleUrlAuthenticationFailureHandler.java:onAuthenticationFailure:67) Redirecting to /krams/auth/login?error=true


т.е. теперь лог сформирован условно правильно
Код: java
1.
[DEBUG] [http-bio-8080-exec-9 09:58:21] (BindAuthenticator.java:bindWithDn:108) Attempting to bind as uid=mmuster,ou=people,dc=springframework,dc=org


эффект тот же. Если я правильно понимаю работу spring-security, то когда пользователь вводит свои данные в login-форму, то framework берет"ник" пользователя ("mmuster") и подставляет его в шаблон предоставленный в файле конфигурации:
Код: java
1.
2.
3.
<security:authentication-manager>
	         <security:ldap-authentication-provider user-dn-pattern="uid={0},ou=people"/>
	</security:authentication-manager>


т.е. пользователь ищется по UID=mmuster, в папке ( O rganisation U nit) "PEOPLE", что фактически так и есть. Моя команда search как раз и выдала структуру папки "people":
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
admin@linux:~/Dokumente/howto> ldapsearch -D "cn=admin,dc=springframework,dc=org" -w secret -b "ou=people,dc=springframework,dc=org" -s sub

# people, springframework.org
dn: ou=people,dc=springframework,dc=org
objectClass: organizationalUnit
objectClass: top
ou: people

# muster mustermann + mustermann + mmuster + 123456, people, springframework.
 org
dn: cn=muster mustermann+sn=mustermann+uid=mmuster+userPassword=123456,ou=peop
 le,dc=springframework,dc=org
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
userPassword:: MTIzNDU2
uid: mmuster
sn: mustermann
cn: muster mustermann


uid: mmuster

а вот то что в файле конфигурации обозначенно как
Код: java
1.
<security:ldap-server url="ldap://localhost:389/dc=springframework,dc=org" manager-dn="cn=admin" manager-password="secret" />


как раз и используется для подключения к серверу LDAP, т.е. url, пользователь и паспорт.

Т.е. я поэтому и застопорился. Я не понимаю где ошибка и почему это не работает
...
Рейтинг: 0 / 0
07.06.2016, 11:47
    #39251778
Atum1
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
Документацию смотреть + тесты и исходники на github

https://spring.io/guides/gs/authenticating-ldap/

Пишите тесты по коду у вас ничего не понять ...

тест такой (JUnit):
arm_test.properties
Код: java
1.
2.
3.
4.
#ldap
ldap.domain=my.office
ldap.url=ldap://dc-1.my.office:389
ldaps.url=ldaps://dc-1.my.office:636




Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {LdapTest.class})
@PropertySource(value = "classpath:arm_test.properties", ignoreResourceNotFound = false)
public class LdapTest {

    protected final Log logger = LogFactory.getLog(getClass());

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        return configurer;
    }

    @Value("${ldap.domain}")
    private String ldapDomain;

    @Value("${ldap.url}")
    private String url;

    @Value("${ldaps.url}")
    private String surl;

    @Value("${email.username}")
    private String username;

    @Value("${email.password}")
    private String password;

    @Autowired
    private Environment environment;

    @Autowired
    AuthenticationSource authenticationSource;

    @Bean
    AuthenticationSource authenticationSource() {
        return new SpringSecurityAuthenticationSource();
    }



    @Autowired
    private LdapTemplate ldapTemplate;
    
    @Autowired
    private LdapTemplate ldapTemplateTechnicalUsers;


    @Bean
    LdapTemplate ldapTemplate() {
        logger.info(TextHelper.hashSignDelimeter(url));
        LdapTemplate ldap = new LdapTemplate(contextSource());
        return ldap;
    }
    @Bean
    LdapTemplate ldapTemplateTechnicalUsers() {
        logger.info(TextHelper.hashSignDelimeter(url));
        LdapTemplate ldap = new LdapTemplate(contextSourceTechnicalUsers());
        return ldap;
    }



    public List getAllPersonNames() {
        System.out.println(ldapTemplate.search("", "(&(objectCategory=person)(objectClass=user))", (AttributesMapper) (Attributes attrs) -> attrs.get("cn").get()).size());
        return ldapTemplate.search("", "(&(objectCategory=person)(objectClass=user))", (AttributesMapper) (Attributes attrs) -> attrs.get("cn").get());
    }




    @Test
    public void testLogin() {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectCategory", "person"));
        filter.and(new EqualsFilter("objectclass", "user"));
        filter.and(new EqualsFilter("cn", username)); //
        System.out.println(filter.toString());
        boolean isauthenticate = ldapTemplateTechnicalUsers.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);
        assertEquals("!= ", isauthenticate, true);
    }



    @Test
    public void testsearch1() {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectCategory", "person"));
        filter.and(new EqualsFilter("objectclass", "user"));
        filter.and(new EqualsFilter("cn", "Иванов Иван Иванович")); //TODO  только по 
        System.out.println(filter.toString());
       ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.toString(), (AttributesMapper) (Attributes attrs) -> attrs.get("memberof").get() ).forEach(System.out::println);
        System.out.println("");
        //ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.toString(), (AttributesMapper) (Attributes attrs) -> attrs.get("managedobjects").get() ).forEach(System.out::println);
        
        
    }


    @Test
    public void testLdapRealUsers() {
        // ldapTemplate.setDefaultCountLimit(10);
        //ldapTemplate.setDefaultSearchScope(10);
        ldapTemplate.search("", "(&(objectCategory=person)(objectClass=user))", (AttributesMapper) (Attributes attrs) -> attrs).stream().limit(5).forEach(System.out::println);
    }

    @Test
    public void testLdapQuery() {
        LdapQuery query = query()
                .base("DC=my,DC=office")
                .searchScope(SearchScope.ONELEVEL)
                //.timeLimit(200)
                //.countLimit(221)
                .where("objectCategory").is("person").and("objectclass").is("user");
        //.where("objectclass").is("user").and("cn").is("Иванов Иван Иванович");

        System.out.println(query.toString());

        ldapTemplate.search(query, (AttributesMapper) (Attributes attrs) -> attrs).stream().limit(10).forEach(System.out::println);
    }

    @Ignore
    @Test
    public void testLdap() {
        getAllPersonNames().stream().limit(10).forEach(System.out::println);
    }

...
Рейтинг: 0 / 0
08.06.2016, 17:27
    #39253071
kadet
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
Atum1,

спасибо за ссылку, проработал.

Я смог немного продвинутся только в результате следующих изменений:

1. старое значение
Код: java
1.
 <security:ldap-server url="ldap://localhost:389/dc=springframework,dc=org" manager-dn="cn=admin" manager-password="secret" /> 


новое значение
Код: java
1.
 <security:ldap-server url="ldap://localhost:389/dc=springframework,dc=org" /> 



2. подчистил правила поиска необходимых величин
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
 	        <security:ldap-authentication-provider  
	        		user-search-filter="(uid={0})" 
	        		user-search-base="ou=people"
	        		
	        		group-search-filter="(uniqueMember={0})"
	        		group-search-base="ou=groups"
	        		group-role-attribute="cn"
	        		role-prefix="ROLE_" 
	        	       		/>   



По §2 это уже дело техники.
По §1 я просто не понимаю, почему LDAP-сервер "проглатил" анонимный доступ, а авторизированный доступ принципиально не работает. Это так задуманно изначально или я действительно чего-то не понимаю ?

За пример тестов спасибо. Буду обязательно отрабатывать.
...
Рейтинг: 0 / 0
08.06.2016, 18:09
    #39253098
mayton
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
kadet, ты качни себе какой-нить Softerra LDAP browser. И залогонься анонимосом.
Потом зайди под cn=admin и получи код ошибки и описание.

По кодам ошибки - погугли LDAP+ERROR+CODES. Возможно формат логина должен быть другой.

Удачи.
...
Рейтинг: 0 / 0
09.06.2016, 09:30
    #39253300
Atum1
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ldap: connection from spring project
kadet,

Еще раз напиши тест :

у тебя в руках есть ldapTemplate - он тебе дает возможность авторизоаватья - подтвердить авторизацию ...

алгоритм такой - твой спринг слой делает редирект на ldap - и там проверяется логин и пароль пользователя ... если все ок тебе возвращается принципал с ролями ... как я понял тебе он и нужен со списком ролей ...

тебе никто не мешает реализовать свой implements AuthenticationProvider

туда заинжектить LdapTemplate и проверять их через свою форму и метод

ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), "Парроль");

+
можно вообще все свое реализовать :

Код: java
1.
2.
3.
4.
5.
ExAuthorizationToken extends UsernamePasswordAuthenticationToken

ExAuthorizationFilter extends UsernamePasswordAuthenticationFilter {

ExAuthenticationManager implements AuthenticationManager 




Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
    @Autowired
    private LdapTemplate ldapTemplate;

    @Test
    public void testRealUsersSearch() {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectCategory", "person"));
        filter.and(new EqualsFilter("objectclass", "user"));
        filter.and(new EqualsFilter("cn", "Иванов Иван Иванович")); 
        System.out.println(filter.toString());
        boolean  isauthenticate = ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), "*Парроль");
        assertEquals("!= ", isauthenticate, true);
       
    }



скорее всего ошибка в фильтрах поиска ... в них всегда ошибка при составлении этого фильтра - выясни у безопасников
какой фильтр даст тебе реальных пользователей ...
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / ldap: connection from spring project / 10 сообщений из 10, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]