【发布时间】:2021-11-12 23:17:12
【问题描述】:
我正在尝试在 Spring Boot (2.5.3) 中进行基本身份验证,并在 DB 中找不到用户时调用 UserNotFoundException。
@Override
public User findByUserName(String username){
try {
return (User) template.queryForObject("SELECT * FROM USERS WHERE email = ?",
new BeanPropertyRowMapper(User.class), username);
} catch (EmptyResultDataAccessException e) {
throw new UsernameNotFoundException("User not found");
}
}
但结果我收到消息“凭证错误”。我的异常已被 BadCredential Exception 更改。
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ex) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
//HttpStatus.FORBIDDEN
Map<String, Object> data = new HashMap<>();
data.put(
"timestamp",
Calendar.getInstance().getTime());
data.put(
"exception",
ex.getMessage());
System.out.println(ex.getClass());
response.getOutputStream()
.println(objectMapper.writeValueAsString(data));
}
class org.springframework.security.authentication.BadCredentialsException
我应该重写什么才能看到 UserNotFoundException 错误消息?
【问题讨论】:
标签: spring-boot spring-mvc spring-security