sjain
sjain

Reputation: 23344

spring security bad credentials distinguish between invalid username or password

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

Answers (1)

JEY
JEY

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 a BadCredentialsException if a username is not found or the password is incorrect. Setting this property to false will cause UsernameNotFoundExceptions to be thrown instead for the former. Note this is considered less secure than throwing BadCredentialsException 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

Related Questions