一尘不染

Spring Boot-外部Tomcat Server Ajax身份验证失败消息

tomcat

Spring Boot用来将.war文件部署到external Tomcat Server

我正在使用Ajax/Restful身份验证,并且具有以下处理身份验证失败的类:

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
}

当我使用嵌入式Tomcat服务器时,一切顺利,并且在身份验证失败时,我得到以下JSON:

{
  "timestamp" : "2015-12-14T15:39:07.365+0000",
  "status" : 401,
  "error" : "Unauthorized",
  "message" : "You have provided wrong credentials",
  "path" : "/api/authentication"
}

但是,当使用时,External Tomcat Server我得到的HTML响应会带来通常的Tomcat失败的身份验证页面。有什么办法可以绕过外部服务器吗?


阅读 249

收藏
2020-06-16

共1个答案

一尘不染

解决方案就是不使用sendError()并提供状态代码并提供自定义异常序列化:

@Service
public class AjaxAuthenticationFailureHandler
        extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(exception));
        response.getWriter().flush();
    }


}
2020-06-16