Reputation: 11026
I want to add a bit of logic to my authentication in Spring Boot, check if an account have a specific logic, for example if a date in its account is before the current date.
Where is best placed in a custom filter or in UserDetailsService?
If it's in a filter, is better to extends from any spring class?
Explanation
As you can see bellow I use a custom userDetailsService() to get the users details (CuentaUser
) in which there are the fields needed for the logic (for example the expiration date). So now I need to add the logic and comes to me two places where I can put it: in UserDetailsServices (throwing an exception if the logic fails) or as a custom filter.
Where is better to put my custom the authentication logic?
This is my actual security configuration:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CuentaRepository accountRepository;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return (username) -> accountRepository.findByUsuario(username)
.map(a -> new CuentaUser(a, AuthorityUtils.createAuthorityList("USER", "write")))
.orElseThrow(() -> new UsernameNotFoundException("could not find the user '" + username + "'"));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
CsrfTokenResponseHeaderBindingFilter csrfTokenFilter = new CsrfTokenResponseHeaderBindingFilter();
http.addFilterAfter(csrfTokenFilter, CsrfFilter.class);
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
Edit: I found that for the example of expiration date, UserDetails have an attribute for it, so is better to use it. Anyway you need to check it with a custom AuthenticationProvider if you don't use the default.
Upvotes: 0
Views: 392
Reputation: 8334
You can use an AuthenticationProvider and put the login inside it.
@Component public class CustomAuthenticationProvider implements AuthenticationProvider {
You can see more here:
http://www.baeldung.com/spring-security-authentication-provider
Upvotes: 2