Reputation: 23344
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);
}
}
Upvotes: 3
Views: 7792
Reputation: 7123
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
AbstractUserDetailsAuthenticationProvider
throws aBadCredentialsException
if ausername
is not found or thepassword
is incorrect. Setting this property tofalse
will causeUsernameNotFoundException
s to be thrown instead for the former. Note this is considered less secure than throwingBadCredentialsException
for 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;
}
Upvotes: 7