我想爲Spring Boot中的身份驗證添加一些邏輯,檢查帳戶是否具有特定的邏輯,例如,如果帳戶中的某個日期在當前日期之前。哪裏更好地把我的自定義驗證邏輯?
哪裏最好放在自定義過濾器或UserDetailsService中?
如果它在過濾器中,最好是從任何春季級別延伸?
說明
正如你可以看到波紋管我用一個自定義的UserDetailsService()來獲得用戶的詳細信息(CuentaUser
),其中有所需的邏輯域(例如到期日期)。所以現在我需要添加邏輯,並在我可以放置的兩個地方找到它:在UserDetailsServices(如果邏輯失敗時拋出異常)或作爲自定義過濾器。
哪裏更好地把我的自定義身份驗證邏輯?
這是我的實際安全配置:
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();
}
}
編輯:我發現,對於到期日期的例子,是UserDetails有它的屬性,因此是更好地使用它。無論如何,如果您不使用默認值,您需要使用自定義AuthenticationProvider進行檢查。