You need to enable JavaScript to run this app. Spring Security搭配Logbook时登录失败如何获取HTTP请求/响应体日志
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security搭配Logbook时登录失败如何获取HTTP请求/响应体日志

问题描述

我想在Spring Security中记录HTTP请求/响应的日志,目前登录成功时日志记录正常,但登录失败时无法获取到请求/响应体。我使用的是Lombok的slf4j以及zalando logbook library。
以下是我的spring-security配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/test/get/**").hasAnyRole("USER")
            .antMatchers("/test/get-all").hasRole("ADMIN")
            .antMatchers("/test/save").hasRole("ADMIN")
            .and()
            .formLogin()
            .permitAll()
            .and()
            .httpBasic();
}

登录成功时我可以拿到如下日志(包含响应体):

{"origin":"local","type":"response","body":"I am saving {\"str\": \"Hello world\"\r\n}"}

登录失败时拿到的响应日志没有body:

{"origin":"local","type":"response", "X-XSS-Protection":["1; mode=block"]}}

请问登录失败时如何才能获取到请求/响应的body内容?


解决方案

核心原因

  • Spring Security的认证相关Filter默认优先级高于Logbook Filter,登录失败时响应会在Logbook读取前就被提交,且默认的响应流只能读取一次,被Security消费后Logbook无法获取内容
  • 默认的表单登录/HttpBasic认证失败处理器要么返回重定向无响应体,要么写入响应后直接关闭流,没有留给Logbook读取的空间

操作步骤

1. 调整Logbook Filter优先级

让Logbook Filter在Spring Security Filter之前执行,提前包装请求/响应为可重复读取的流,Spring Boot中直接在配置文件添加如下配置即可:

# Spring Security默认Filter优先级为-100,设置更小的值即可让Logbook更早执行
logbook.filter.order = -110

2. 自定义认证失败处理器,明确写入响应体

默认的登录失败处理器会触发重定向,没有实际响应体内容,需要自定义处理器返回结构化的错误信息,同时适配前后端分离的接口场景:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("message", "登录失败:" + exception.getMessage());
        
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}

3. 更新Spring Security配置

把自定义的失败处理器注册到安全配置中,同时如果使用HttpBasic认证,也要补充认证入口的异常处理:

@Autowired
private LoginFailureHandler loginFailureHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/test/get/**").hasAnyRole("USER")
            .antMatchers("/test/get-all").hasRole("ADMIN")
            .antMatchers("/test/save").hasRole("ADMIN")
            .and()
            .formLogin()
            .failureHandler(loginFailureHandler) // 注册自定义登录失败处理器
            .permitAll()
            .and()
            .httpBasic()
            .and()
            // 处理HttpBasic等其他认证场景的失败响应
            .exceptionHandling()
            .authenticationEntryPoint((request, response, authException) -> {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.getWriter().write("{\"code\":401,\"message\":\"认证失败,请检查账号密码\"}");
            });
}

4. 检查Logbook配置

确保没有排除登录接口,且开启了响应体记录:

# 不要将登录接口加入排除列表
logbook.exclude=
# 开启响应体记录
logbook.include-response-body=true

内容的提问来源于stack exchange,提问作者Umaralikhon Kayumov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:36:01