gpt4 book ai didi

java - spring security 错误凭证区分无效的用户名或密码

转载 作者:行者123 更新时间:2023-11-30 06:38:01 24 4
gpt4 key购买 nike

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

来自文档: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
}
}

更新:

 public class SampleDaoAuthenticationProvider extends DaoAuthenticationProvider {

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

最佳答案

警告:这样做不是良好的安全实践。但是,如果您确实不想隐藏 UsernameNotFoundException,您可以配置 AuthenticationProvider(如果它从 AbstractUserDetailsAuthenticationProvider 扩展)来抛出它而不是使用 setHideUserNotFoundExceptions 实现 BadCredentialException

JavaDoc 摘录:

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.

示例:

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

关于java - spring security 错误凭证区分无效的用户名或密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44881171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com