问题
In Spring Security, we can get the bad credentials exception if the username/password are not correct.
From DOC: Spring Framework Authentication
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
org.springframework.security.core.AuthenticationException
org.springframework.security.authentication.BadCredentialsException
Is there any exception class or way to distinguish between username invalid OR password invalid?
Something like the following:
catch(BadCredentialsException e) {
if(usernameInvalid) {
// invalid username
} else {
// password invalid
}
}
UPDATE:
public class SampleDaoAuthenticationProvider extends DaoAuthenticationProvider {
@Override
protected void additionalAuthenticationChecks(UserDetails
userDetails, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
setHideUserNotFoundExceptions(false);
super.additionalAuthenticationChecks(userDetails, authentication);
}
}
回答1:
Warning: it's not good security practice to do so.
But if you realy don't want to hide UsernameNotFoundException you can configure the AuthenticationProvider (if it extends from AbstractUserDetailsAuthenticationProvider) to throw it instead of a BadCredentialException by using setHideUserNotFoundExceptions.
JavaDoc Extract:
By default the
AbstractUserDetailsAuthenticationProviderthrows aBadCredentialsExceptionif ausernameis not found or thepasswordis incorrect. Setting this property tofalsewill causeUsernameNotFoundExceptions to be thrown instead for the former. Note this is considered less secure than throwingBadCredentialsExceptionfor both exceptions.
example:
@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;
}
来源:https://stackoverflow.com/questions/44881171/spring-security-bad-credentials-distinguish-between-invalid-username-or-password