Spring Security 自定义登录回退

Posted

技术标签:

【中文标题】Spring Security 自定义登录回退【英文标题】:Spring Security Custom Login Fallback 【发布时间】:2021-09-13 03:32:36 【问题描述】:

有人可以向我指出一些资源,这些资源可以指导我如何实现自定义 spring 安全身份验证,如果该用户存在 ldap 用户名字段,则首先在 ldap 服务器上测试找到的用户的凭据, 并且无法进行身份验证(因为 ldap 用户名不存在或给定的密码未对服务器上的用户名进行身份验证),将尝试针对在本地数据库中为用户保留散列的本地密码进行身份验证。

谢谢。

【问题讨论】:

您可以阅读 docs 并尝试来自 Spring Security 的 sample 【参考方案1】:

对于该特定问题,似乎没有太多好的答案。

虽然我还没有建立一个完整的工作 LDAP 示例,但应该有一个良好的开始在 @Marcus 在 cmets 中链接的 ldap sample 中的那部分。话虽如此,您可以轻松地按照您想要的顺序注册两个身份验证提供程序,默认的DaoAuthenticationProvider 是第二个:

@Configuration
public class SecurityConfiguration 

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception 
        // @formatter:off
        return http
            .authorizeRequests(authorizeRequests -> authorizeRequests
                .anyRequest().authenticated()
            )
            .formLogin(withDefaults())
            .authenticationProvider(ldapAuthenticationProvider())
            .authenticationProvider(daoAuthenticationProvider())
            .build();
        // @formatter:on
    

    @Bean
    public AuthenticationProvider ldapAuthenticationProvider() 
        LdapContextSource contextSource = null; // TODO See sample for example
        return new LdapAuthenticationProvider(new BindAuthenticator(contextSource));
    

    @Bean
    public AuthenticationProvider daoAuthenticationProvider() 
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        return authenticationProvider;
    

    @Bean
    public UserDetailsService userDetailsService() 
        UserDetails userDetails = User.builder()
            .username("user")
            .password("nooppassword")
            .roles("USER")
            .build();

        return new InMemoryUserDetailsManager(userDetails);
    


您显然希望提供自己的用户详细信息,该详细信息使用数据库而不是内存。 username-password sample 可以让您开始使用,您可以将该示例中的 MapCustomUserRepository 替换为例如一个弹簧数据@Repository

【讨论】:

以上是关于Spring Security 自定义登录回退的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security 入门 我们在篇中已经谈到了默认的登录页面以及默认的登录账号和密码。 在这一篇中我们将自己定义登录页面及账号密码。 我们先从简单的开始吧:设置自定

未调用 Spring Security 自定义登录表单

Spring Security3.0怎样自定义登录,后台自定义参数传递

自定义登录表单无法使用 Spring Security

Spring Security自定义登录页面

Spring Security 自定义登录认证