学习使用简单的开关为Spring安全配置、请求处理和过滤链代理启用DEBUG和TRACE级别的日志。使用TRACE进行更广泛的日志记录,以了解更深层次的情况。
1.设置日志级别
Spring security在记录器名称org.springframework.security 下记录语句。我们可以该日志器的日志级别来启用任何级别的日志。
对于Spring boot应用程序,我们可以直接在属性文件中配置日志级别。
logging.level.org.springframework.security=DEBUG # Or TRACE
YAML 语法是 :
logging:
level:
org:
springframework:
security: DEBUG
对于非Spring boot应用程序,我们可以编辑日志配置文件(如*logback.xml或log4j2.xml)并设置日志级别。例如,在logback.xml*中,以下单行配置就足以启用spring security模块的调试日志。
<logger name="org.springframework.security" level="DEBUG" />
2.使用 @EnableWebSecurity(debug = true)
debug 参数控制Spring Security的调试支持。默认情况下,debug为false。
这个debug 开关有助于在日志中记录完整的认证请求。
@EnableWebSecurity(debug = true)
public class SecurityConfiguration
extends WebSecurityConfigurerAdapter {
}
在开发过程中,可以临时启用调试开关,但在生产环境中决不能使用调试日志。如果我们想为特定的部署配置文件启用该开关,那么我们可以在该环境中把下面的属性设置为真。
org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=true
3.使用属性spring.websecurity.debug
另一个控制Spring安全调试的好办法是使用WebSecurity.debug() 方法。我们可以在运行时向该方法注入一个true/false的属性值来控制调试日志。
在下面的例子中,我们在运行时注入了属性spring.websecurity.debug 的值。默认值是false。
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${spring.websecurity.debug:false}")
boolean webSecurityDebug;
@Override
public void configure(WebSecurity web) throws Exception {
web.debug(webSecurityDebug);
}
}
4.4.演示
让我们用一个简单的测试案例来看看我们在spring安全级别上启用调试日志时的日志。
@Test
void expectOKResponse_WhenPasswordIsCorrect() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/")
.with(httpBasic("user", "password")))
.andExpect(content().string("Hello World !!"));
}
它将产生以下日志。一个真正的应用程序会产生许多其他有用的日志语句,这个例子只是为了让你有一个高度的了解。
00:46:49.345 [main] WARN o.s.s.c.a.web.builders.WebSecurity -
********************************************************************
********** Security debugging is enabled. *************
********** This may include sensitive information. *************
********** Do not use in a production system! *************
********************************************************************
Request received for GET '/':
org.springframework.mock.web.MockHttpServletRequest@351f2244
servletPath:
pathInfo:/
headers:
Authorization: Basic dXNlcjpwYXNzd29yZA==
Security filter chain: [
DisableEncodeUrlFilter
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
5.总结
在本教程中,我们学习了如何在spring安全认证和授权中启用调试和跟踪级别的日志记录。推荐的方法是使用配置文件的特定属性并使用指定的开关来打开/关闭调试日志。
学习愉快!!