Spring Security Spring LDAP返回相同且不正确的objectSid

c9qzyr3d  于 2023-08-05  发布在  Spring
关注(0)|答案(3)|浏览(98)

在我的Spring Web应用程序中,我无法从使用Active Directory帐户的当前登录用户中检索正确的objectId。所有的属性似乎都有正确的值,但是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) {

    }
}


如何从Active Directory中获取正确的SID?

hkmswyz6

hkmswyz61#

我想答案就在这里: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
This thread还描述了一种编程方式来设置该属性(尽管对于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();

5ssjco0h

5ssjco0h2#

我通过在configure方法中添加环境属性来实现这一点:

@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"));    
}


我希望这是有帮助的!

dgenwo3n

dgenwo3n3#

这不是关于Spring的,而是关于普通的JavaLDAP访问(以防有人发现这个页面在寻找它--就像我一样)。在构建DirContext时,需要告诉它将objectSid保持为二进制形式。否则,它将尝试将字节解码为String,这将用unicode REPLACEMENT CHARACTER U+FFFD(�)替换无效字符-从而无法获得正确的Sid。

DirContext ldapConnect() throws NamingException {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapServer);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapUser);
    env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

    env.put("java.naming.ldap.attributes.binary", "objectSid"); // !!!!!!!!!!!!!!!!!!
    return new InitialDirContext(env);
}

字符串
这基本上是Gabriel Lucis的答案,只是为了香草Java而不是Spring。

相关问题