如果登录失败,如何在springsecurity中获取http请求/响应的主体作为日志



我正在尝试获取spring-security中http请求/响应的日志。登录成功也没问题。但当登录失败时,我无法获取身体。我正在使用lombok的slf4j和zalando日志库。

这是我的春季安全配置:

@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"rn}"}

如果登录失败,我会得到没有正文的响应:

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

如果登录失败,如何获取响应/请求的正文?

您似乎正在使用formLogin(),因此可以执行以下操作:

http
.formLogin()
.failureHandler((req, res, authentication) -> /*do whatever you want with req, res and authentication*/)
...

AuthenticationFailureHandler接口定义了一种方法,在该方法中可以使用HTTP请求、响应和Authentication对象。

void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)

最新更新