Spring Security - 首先在DB中验证用户,然后针对AD进行身份验证

时间:2017-05-18 12:05:54

标签: java spring security

我们需要验证数据库中是否存在用户名,然后针对AD进行身份验证。如果用户名不存在,应用程序将返回错误,而不是尝试对AD进行身份验证。我已经对多个AD和/或数据库进行了身份验证,但是我无法使用它。任何提示都会有所帮助。谢谢

在扩展WebSecurityConfigurerAdapter的课程中,我尝试使用authenticationProvider来验证数据库中是否存在。但不确定要返回什么,以便身份验证可以继续进行到LDAP。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
     .authenticationProvider(authenticationProvider)
    .authenticationEventPublisher(authenticationEventPublisher)
    .ldapAuthentication()
    .....;

}

我还尝试添加一个前/后过滤器但在那里没有成功

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
   ....
 .and()
 .addFilterBefore(preAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
;

1 个答案:

答案 0 :(得分:0)

在过滤器preAuthenticationFilter中,在doFilter()方法FirewalledRequest中传递请求的实例。从这个例子我无法获得用户名;看起来这是设计的。如果有人对如何从FirewalledRequest实例中检索用户名有任何建议,请在此处分享。我试试看。

因此,我决定使用自定义AuthenticationProvider而不是使用过滤器。在authenticate()方法下的AuthenticationProvider实现中,当用户存在时,我返回null(和log,notify等)。如果用户没有退出,我返回相同的身份验证实例。这会破坏链并停止继续对AD进行身份验证。抛出AuthenticationException的任何实例都不起作用,因为Spring安全性捕获此异常并继续进行(每个文档)。

以下是代码段的外观

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
    Optional<User> user = service.findUserByUsername((String) authentication.getPrincipal());

    if (user.isPresent())
        return null;

    return authentication;
}

请分享任何更好的想法。