spring security bad credentials distinguish between invalid username or password

早过忘川 提交于 2020-06-28 06:21:55

问题


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 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;
    }


来源:https://stackoverflow.com/questions/44881171/spring-security-bad-credentials-distinguish-between-invalid-username-or-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!