Spring Boot - 外部Tomcat服务器Ajax身份验证失败消息

时间:2015-12-14 15:54:34

标签: ajax spring tomcat authentication spring-boot

我正在使用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失败身份验证页面。有没有办法绕过外部服务器?

1 个答案:

答案 0 :(得分:0)

解决方案只是不使用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();
    }


}