1、概览 {#1概览}
使用 Spring Security 时,可能需要把日志级别设置得更高一些。例如,可能需要检查用户的角色或端点的安全配置。或者,可能还需要更多关于身份认证或授权的信息,例如查看为什么用户无法访问某个端点。
本文将带你了解如何修改 Spring Security 日志级别。
2、配置 Spring Security 日志 {#2配置-spring-security-日志}
与其他 Spring 或 Java 应用一样,可以使用日志库,并为 Spring Security 模块定义日志级别。
通常,可以进行如下配置:
<logger name="org.springframework.security" level="DEBUG" />
如果运行的是 Spring Boot 应用,则可以在 application.properties
文件中对此进行配置:
logging.level.org.springframework.security=DEBUG
同样,也可以使用 yaml:
logging:
level:
org:
springframework:
security: DEBUG
这样,就可以查看有关身份认证或 Filter Chain 的日志。此外,还可以使用 trace
级别进行更深入的 debug。
Spring Security 还能记录有关请求和应用的 Filter 的特定信息:
@EnableWebSecurity
public class SecurityConfig {
@Value("${spring.websecurity.debug:false}")
boolean webSecurityDebug;
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.debug(webSecurityDebug);
}
// ...
}
3、日志示例 {#3日志示例}
定义一个简单的 Controller 来测试应用:
@Controller
public class LoggingController {
@GetMapping("/logging")
public ResponseEntity<String> logging() {
return new ResponseEntity<>("logging/baeldung", HttpStatus.OK);
}
}
访问 /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
]
参考:https://www.baeldung.com/spring-security-enable-logging