spring security 坏凭据区分无效的用户名或密码

My *_*God 3 java spring-security

在 Spring Security 中,如果用户名/密码不正确,我们可能会收到错误凭据异常。

来自 DOC:Spring 框架身份验证

java.lang.Object
  java.lang.Throwable
    java.lang.Exception
      java.lang.RuntimeException
        org.springframework.security.core.AuthenticationException
         org.springframework.security.authentication.BadCredentialsException
Run Code Online (Sandbox Code Playgroud)

是否有任何异常类或方法来区分用户名无效或密码无效?

类似于以下内容:

catch(BadCredentialsException e) {
    if(usernameInvalid) {
        // invalid username
    } else {
        // password invalid
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

 public class SampleDaoAuthenticationProvider extends DaoAuthenticationProvider {

        @Override
        protected void additionalAuthenticationChecks(UserDetails 
userDetails, UsernamePasswordAuthenticationToken authentication)
                throws AuthenticationException {
                setHideUserNotFoundExceptions(false);
                super.additionalAuthenticationChecks(userDetails, authentication);
        }
    }
Run Code Online (Sandbox Code Playgroud)

JEY*_*JEY 5

警告:这样做不是很好的安全做法。 但是如果你真的不想隐藏UsernameNotFoundException你可以配置AuthenticationProvider(如果它从 扩展AbstractUserDetailsAuthenticationProvider)来抛出它而不是BadCredentialException使用setHideUserNotFoundExceptions

JavaDoc 提取:

默认情况下,如果 a未找到或不正确,则AbstractUserDetailsAuthenticationProvider抛出 a 。将此属性设置为将导致s 被抛出而不是前者。请注意,这被认为比抛出两个异常更不安全。BadCredentialsExceptionusernamepasswordfalseUsernameNotFoundExceptionBadCredentialsException

例子:

@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;
    }
Run Code Online (Sandbox Code Playgroud)