2017-07-03 88 views
1

在Spring Security中,如果用戶名/密碼不正確,我們可能會得到錯誤的證書異常。彈簧安全性錯誤憑據區分無效的用戶名或密碼

從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 

是否有任何異常類或方法無效的用戶名或密碼無效的區分?

類似以下內容:

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); 
     } 
    } 
+0

我會做呼叫setHideUserNotFoundException在構造函數來代替。 – JEY

+0

哪個構造函數?我只能在這裏看到void方法。你說使用構造函數SampleDaoAuthenticationProvider來初始化它我認爲。 –

+0

添加一個公共SampleDaoAuthenticationProvider(){super(); setHideUserNotFoundException(false);} – JEY

回答

0

警告:這不是良好的安全習慣這樣做。 但是,如果您真的不想隱藏UsernameNotFoundException,則可以使用setHideUserNotFoundExceptions配置AuthenticationProvider(如果它從AbstractUserDetailsAuthenticationProvider延伸)以代替BadCredentialException而不是BadCredentialException

JavaDoc中摘錄:

默認情況下,AbstractUserDetailsAuthenticationProvider拋出一個BadCredentialsException如果username沒有找到或password不正確。將該屬性設置爲false將導致UsernameNotFoundException代替前者。請注意,對於這兩個例外,這被認爲比投擲BadCredentialsException更安全。

例如:

@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; 
    } 
+0

我有一個擴展了DaoAuthenticationProvider的類,該類重寫了Spring的additionalAuthenticationChecks()方法。我可以從那裏訪問setHideUserNotFoundExceptions。所以我相信我可以在那個類中使用這個setter方法。 –