Java spring security错误凭据区分无效用户名或密码
在SpringSecurity中,如果用户名/密码不正确,我们可以得到错误的凭据异常 从文件: 是否有任何异常类或方法来区分用户名无效或密码无效 如下所示:Java spring security错误凭据区分无效用户名或密码,java,spring-security,Java,Spring Security,在SpringSecurity中,如果用户名/密码不正确,我们可以得到错误的凭据异常 从文件: 是否有任何异常类或方法来区分用户名无效或密码无效 如下所示: catch(BadCredentialsException e) { if(usernameInvalid) { // invalid username } else { // password invalid } } 更新: public class SampleDaoAuthe
catch(BadCredentialsException e) {
if(usernameInvalid) {
// invalid username
} else {
// password invalid
}
}
更新:
public class SampleDaoAuthenticationProvider extends DaoAuthenticationProvider {
@Override
protected void additionalAuthenticationChecks(UserDetails
userDetails, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
setHideUserNotFoundExceptions(false);
super.additionalAuthenticationChecks(userDetails, authentication);
}
}
警告:这样做不是好的安全做法。 但是如果您确实不想隐藏
用户名NotFoundException
,您可以通过使用setHideUserDetailsAuthenticationProvider
配置身份验证提供程序
(如果它扩展自AbstractUserDetailsAuthenticationProvider
)来抛出它,而不是不良身份验证
JavaDoc摘录:
默认情况下,AbstractUserDetailsAuthenticationProvider
在未找到用户名或密码不正确时抛出BadCredentialsException
。将此属性设置为false
将导致为前者引发UsernameNotFoundException
s。注意:对于这两种异常,这被认为不如抛出BadCredentialsException
安全
例如:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider())
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
impl.setUserDetailsService(yourUserDetailsService());
impl.setPasswordEncoder(new BCryptPasswordEncoder());
impl.setHideUserNotFoundExceptions(false) ;
return impl;
}
我有一个扩展DaoAuthenticationProvider的类,该类重写Spring的additionalAuthenticationChecks()方法。我可以从那里访问setHideUserNotFoundExceptions。所以我相信我可以在那个类中使用setter方法。我会在构造函数中调用setHideUserNotFoundException。哪个构造函数?我在这里只能看到void方法。我想您是说使用构造函数SampleDaoAuthenticationProvider来初始化它。添加一个公共SampleDaoAuthenticationProvider(){super();setHideUserNotFoundException(false);}所以现在如果用户名不正确,那么我将获得用户名NotFoundException,如果密码不正确,那么我将获得BadCredentialException?从而区分两者,解决我的问题。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider())
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
impl.setUserDetailsService(yourUserDetailsService());
impl.setPasswordEncoder(new BCryptPasswordEncoder());
impl.setHideUserNotFoundExceptions(false) ;
return impl;
}