Spring LDAP возвращает тот же и неправильный objectSid - PullRequest
0 голосов
/ 28 мая 2018

В моем веб-приложении Spring я не могу получить правильный objectId от текущего вошедшего в систему пользователя с учетной записью Active Directory.Кажется, что все атрибуты имеют правильное значение, но значение objectId всегда установлено на S-1-5-21-1723711471-3183472479-4012130053-3220159935, и я не знаю, откуда оно.

WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    private ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider =
                new ActiveDirectoryLdapAuthenticationProvider(LdapConfig.AD_DOMAIN, LdapConfig.AD_SERVER);
        provider.setUserDetailsContextMapper(new LdapUserDetailsContextMapper());
        return provider;
    }
}

LdapUserDetailsContextMapper

@Slf4j
public class LdapUserDetailsContextMapper implements UserDetailsContextMapper {
    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> collection) {
        log.info("username: " + username); //username is correct
        log.info("DN from ctx: " + ctx.getDn()); // returns correct DN
        byte[] byteSid = ctx.getStringAttribute("objectSid").getBytes();
        String sid = LdapUtils.convertBinarySidToString(byteSid);
        log.info("SID: " + sid); // S-1-5-21-1723711471-3183472479-4012130053-3220159935 everytime

        return new User(username, "notUsed", true, true, true, true,
                AuthorityUtils.createAuthorityList("ROLE_USER"));
    }

    @Override
    public void mapUserToContext(UserDetails userDetails, DirContextAdapter dirContextAdapter) {

    }
}

Как получить правильный SID из Active Directory?

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

Я получил это для работы, добавив свойства среды в методе конфигурации:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .authenticationProvider(activeDirectoryLdapAuthenticationProvider());
}

private ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
    ActiveDirectoryLdapAuthenticationProvider provider =
            new ActiveDirectoryLdapAuthenticationProvider(LdapConfig.AD_DOMAIN, LdapConfig.AD_SERVER);

// ************** NEW ENVIRONMENT PROPERTIES **********************************
    Map<String, Object> environmentProperties = new HashMap<>();
    environmentProperties.put("java.naming.ldap.attributes.binary", "objectsid");
    provider.setContextEnvironmentProperties(environmentProperties);
// ************** END OF NEW ENVIRONMENT PROPERTIES ***************************

    provider.setUserDetailsContextMapper(new LdapUserDetailsContextMapper());
    return provider;
    }
}

И затем прочитав это так в UserDetailContextMapper:

public class CustomUserDetailsContextMapper implements UserDetailsContextMapper {

private final static Logger logger = LoggerFactory.getLogger(CustomUserDetailsContextMapper.class);

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
    logger.info(ctx.getDn().toString());
    byte[] byteSid = null;
    try {
        byteSid = (byte[]) ctx.getAttributes().get("objectsid").get();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    String sid = LdapUtils.convertBinarySidToString(byteSid);
    logger.info("SID: {}", sid);

    return new User(username, "notUsed", true, true, true, true,
            AuthorityUtils.createAuthorityList("ROLE_USER"));    
}

Я надеюсь, что этополезно!

0 голосов
/ 28 мая 2018

Я думаю, что ответ здесь: http://forum.spring.io/forum/spring-projects/data/ldap/66894-objectsid-and-ldaptemplate

Во втором последнем посте он описывает ту же проблему, что и у вас.В последнем посте он описывает исправление, которое заключается в добавлении этого в файл конфигурации Bean:

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
    <property name="url" value="ldap://ldapserver.domain.com:389" />
    <property name="base" value="dc=domain,dc=com" />
    <property name="userDn" value="cn=binduser,cn=Users,dc=domain,dc=com" />
    <property name="password" value="bindpwd"/>
    <property name="baseEnvironmentProperties">
        <map>
        <entry key="java.naming.ldap.attributes.binary">
            <value>objectSid</value>
        </entry>
        </map>
    </property>
</bean>

Вам придется изменить значения для вашего домена, но я думаю, что важной частью являетсяbaseEnvironmentProperties.

Этот поток также описывает программный способ установки этого (хотя для objectGuid, но вы можете просто поменять атрибут).

AbstractContextSource contextSource = (AbstractContextSource) ldapTemplate.getContextSource();
Map<String,String> baseEnvironmentProperties = new HashMap<String, String>();
baseEnvironmentProperties.put("java.naming.ldap.attributes.binary", "objectSid");
contextSource.setBaseEnvironmentProperties(baseEnvironmentProperties);
contextSource.afterPropertiesSet();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...