Spring Security - Verify user in DB first and then authenticate against AD

0 投票
最新提问 用户: (160 分)

We have a requirement to verify whether a username exists in database and then authenticate against AD. If username doesnt exist application will return error instead of trying to authenticate against AD. I have authenticated against multiple ADs and/or database but I have trouble getting this to work. Any hints would be helpful. Thank you

In my class that extends WebSecurityConfigurerAdapter I tried to play with authenticationProvider where I could verify the existence in DB. But not sure of what to return so that the authentication could be proceed to LDAP.

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


I also tried adding a before/after filter but not successful in there either

protected void configure(HttpSecurity http) throws Exception {
 .addFilterBefore(preAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
发表于 用户: (100 分)
What have you tried, can we see some codes?
发表于 用户: (160 分)
@andre3wap I added code snippet


0 投票
最新回答 用户: (160 分)

In the filter preAuthenticationFilter the instance of request passed in doFilter() method FirewalledRequest. From this instance I am unable to get the username; looks like this is by design. If anyone has any advice on how we could retrieve username from the instance of FirewalledRequest please share it here. I will give it a try.

So instead of using the filter I decided to play with the custom AuthenticationProvider. In the AuthenticationProvider implementation under the method authenticate() I return null (and log, notify, etc.) when user exist. If user doesnt exits I return the same instance of authentication passed. This breaks the chain and stops proceeding to authenticating against AD. Throwing any instance of AuthenticationException doesnt work as Spring security captures this exception and proceeds further (per docs).

Here is how the code snippet looks like

@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Optional user = service.findUserByUsername((String) authentication.getPrincipal()); if (user.isPresent()) { return null; } return authentication; }

Please share any better ideas.

欢迎来到 Security Q&A ,有什么不懂的可以尽管在这里提问,你将会收到社区其他成员的回答。