1 回答
TA贡献1827条经验 获得超9个赞
我不得不放弃尝试让 Spring Security 自动为入口点提供来自用户详细信息服务的异常消息的想法。
因此,我改用自定义身份验证提供程序以获得更多控制,并引入了一个名为 ErrorMessage 的自定义服务:
@Getter
@Setter
@ToString
@Service
public class ErrorMessage {
private String status;
private String message;
}
@Getter、@Setter 和@ToString 注释来自 lombok。他们做到了,所以我不必编写 setter 和 getter 以及 toString 方法。
在我的自定义身份验证提供程序中,我只是这样设置错误消息:
private @Autowired ErrorMessage errorMessage;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
try {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
if (!credentials.checkUserExists(username)) {
//set something here
}
memberProfile = credentials.getUserInformation(username);
if (passwordEncoder.matches(password, memberProfile.getPassword())) {
logger.info("It matches - encoder!");
return new UsernamePasswordAuthenticationToken(username, password, getGrantedAuthorities());
} else {
//error message bean utilised here
errorMessage.setStatus("100");
errorMessage.setMessage(username + "'s password is incorrect");
throw new BadCredentialsException("The credentials provided are incorrect");
}
} catch (Exception ex) {
throw new BadCredentialsException("The credentials provided are incorrect", ex);
}
}
然后我以这种方式在入口点获得自定义错误消息:
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
private @Autowired ErrorMessage errorMessage;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
//String json = String.format("{\"errorcode\": \"%s\", \"message\": \"%s\"}", response.getStatus(), ex.getMessage());
String json = String.format("{\"errorcode\": \"%s\", \"message\": \"%s\"}", errorMessage.getStatus(), errorMessage.getMessage());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
添加回答
举报