登陆时,用户名或密码错误如何优化

提问 1 1145
邮箱用户_9sc6b
邮箱用户_9sc6b LV2 2021年6月14日 23:43 发表
点击群号免费加入社区交流群:367346704
<p>登陆时,用户名或密码错误会返回{<br> "error": "invalid_grant",<br> "error_description": "Bad credentials"<br>}</p><p>如何自定义异常处理</p>
收藏(0)  分享
相关标签: spring
1个回复
  • 站长
    2021年6月15日 00:29
    1、自定义验证器的代码示例: [pre] import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class AuthenticationProviderImpl implements AuthenticationProvider { @Autowired @Qualifier("userDetailsServiceImpl") private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username=authentication.getName(); String password=authentication.getCredentials().toString(); Account account=(Account)userDetailsService.loadUserByUsername(username); if(account.isLocked()){ throw new BadCredentialsException("帐号已锁定!"); } if(account.isExpire()){ throw new BadCredentialsException("帐号已过期!"); } if(!new BCryptPasswordEncoder().matches(password,account.getPassword())){ throw new BadCredentialsException("密码错误!"); } return new UsernamePasswordAuthenticationToken(account,account.getPassword(),account.getAuthorities()); } @Override public boolean supports(Class<?> aClass) { return UsernamePasswordAuthenticationToken.class.equals(aClass); } } [/pre] 2、在WebSecurityConfig里使用自定义验证器: [pre] @Autowired @Qualifier("authenticationProviderImpl") private AuthenticationProvider authenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); auth.authenticationProvider(authenticationProvider); } [/pre]
    0 0