Enable Logging for Spring Security – 启用Spring安全的日志记录

最后修改: 2022年 2月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

When using Spring Security, we may need to log to a higher level than the default one. We may need to check, for example, users’ roles or how endpoints are secured. Or maybe we also need more info about authentication or authorization, for example, to see why a user fails to access an endpoint.

当使用Spring Security时,我们可能需要记录到比默认级别更高的水平。我们可能需要检查,例如,用户的角色或端点的安全方式。或者,也许我们还需要更多关于认证或授权的信息,例如,查看用户为什么不能访问某个端点。

In this short tutorial, we’ll see how to modify the Spring Security logging level.

在这个简短的教程中,我们将看到如何修改Spring Security的日志级别。

2. Configure Spring Security Logging

2.配置Spring安全日志

Like any Spring or Java application, we can use a logger library and define a logging level for the Spring Security modules.

与任何Spring或Java应用程序一样,我们可以使用日志库并为Spring Security模块定义一个日志级别

Typically, we can write in our configuration file something like:

通常情况下,我们可以在配置文件中写上类似的内容。

<logger name="org.springframework.security" level="DEBUG" />

However, if we’re running a Spring Boot application, we can configure this in our application.properties file:

但是,如果我们运行的是Spring Boot应用程序我们可以在application.properties文件中对此进行配置。

logging.level.org.springframework.security=DEBUG

Likewise, we can use the yaml syntax:

同样地,我们可以使用yaml语法。

logging:
  level:
    org:
      springframework:
        security: DEBUG

This way, we can check out logs about the Authentication or the Filter Chain. Moreover, we can even use the trace level for deeper debugging.

这样,我们可以查看关于认证过滤链的日志。此外,我们甚至可以使用trace级别来进行更深入的调试。

Additionally, Spring Security offers the possibility to log specific info about requests and applied filters:

此外,Spring Security提供了记录有关请求和应用过滤器的具体信息的可能性

@EnableWebSecurity
public class SecurityConfig {

    @Value("${spring.websecurity.debug:false}")
    boolean webSecurityDebug;

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.debug(webSecurityDebug);
    }
    // ...
}

3. Log Samples

3.日志样本

Finally, to test our application, let’s define a simple controller:

最后,为了测试我们的应用程序,让我们定义一个简单的控制器。

@Controller
public class LoggingController {

    @GetMapping("/logging")
    public ResponseEntity<String> logging() {
        return new ResponseEntity<>("logging/baeldung", HttpStatus.OK);
    }

}

If we hit the /logging endpoint, we can check our logs:

如果我们打到/logging端点,我们可以检查我们的日志:

2022-02-10 21:30:32.104 DEBUG 5489 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorized filter invocation [GET /logging] with attributes [permitAll]
2022-02-10 21:30:32.105 DEBUG 5489 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Secured GET /logging
2022-02-10 21:30:32.141 DEBUG 5489 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
2022-02-10 21:30:32.146 DEBUG 5489 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
Request received for GET '/logging':

org.apache.catalina.connector.RequestFacade@78fe74c6

servletPath:/logging
pathInfo:null
headers: 
host: localhost:8080
connection: keep-alive
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site: none
sec-fetch-mode: navigate
sec-fetch-user: ?1
sec-fetch-dest: document
accept-encoding: gzip, deflate, br
accept-language: en,it;q=0.9,en-US;q=0.8
cookie: PGADMIN_LANGUAGE=en; NX-ANTI-CSRF-TOKEN=0.7130543323088452; _ga=GA1.1.1440105797.1623675414; NXSESSIONID=bec8cae2-30e2-4ad4-9333-cba1af5dc95c; JSESSIONID=1C7CD365F521609AD887B3D6C2BE26CC


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]

4. Conclusion

4.总结

In this article, we looked at a few options to enable a different logging level for Spring Security.

在这篇文章中,我们看了几个选项来为Spring Security启用不同的日志记录级别。

We’ve seen how to use a debug level for the Spring Security modules. Also, we’ve seen how to log specific info about single requests.

我们已经看到如何为Spring Security模块使用debug级别。此外,我们还看到了如何记录关于单个请求的具体信息。

As always, the code for these examples is available over on GitHub.

一如既往,这些示例的代码可在GitHub上获得