Resource server with Spring Security 5 issue with SecurityContextPersistenceFilter in SpringSecurityChain - spring

I faced a problem with Resource Server in Spring Security 5. I'm using spring security 5.3.7 and spring boot in version 2.7.4 with dependecy:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
My problem is with getting 401 Unauthorized response when I using Postman to get to secured resource. I set up my configuration server according to Spring docs https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html#oauth2resourceserver-jwt-minimaldependencies.
Below it's my configuration:
Controller class:
#PreAuthorize("hasAuthority('EXAMPLE')")
#RestController
public class MyController {
#GetMapping("/example")
public List<Something> myMethod(Principal auth) {
return ...
}
Configuration of my resource server with JWT + Key usecase:
#Configuration
#EnableWebSecurity(debug = true)
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityResourceServerConfig {
#Value("${spring.security.oauth2.resourceserver.jwt.key-value}")
private String signingKey;
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated())
.oauth2ResourceServer((oauth2) -> oauth2.jwt((jwt) -> jwt.decoder(jwtDecoder())))
.cors();
return http.build();
}
#Bean
public JwtDecoder jwtDecoder() {
byte[] secretByte = signingKey.getBytes();
SecretKey secretKey = new SecretKeySpec(secretByte, 0, secretByte.length, "RSA");
return NimbusJwtDecoder.withSecretKey(secretKey).build();
}
#Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
For logging my SecurityFilterChain i added #EnableWebSecurity(debug = true) and to application.yml
logging:
level:
org:
springframework:
security: DEBUG
When I make request to endpoint #GetMapping("/example"). I get 401 Unauthorized code. When I check logs of my service I see:
Security filter chain: [
DisableEncodeUrlFilter
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter
CsrfFilter
LogoutFilter
BearerTokenAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
AuthorizationFilter
]
************************************************************
2022-10-01 16:16:54.912 DEBUG 1 --- , [http-nio-8080-exec-8] o.s.security.web.FilterChainProxy.doFilterInternal - Securing GET /roles
2022-10-01 16:16:54.913 DEBUG 1 --- , [http-nio-8080-exec-8] o.s.s.w.c.SecurityContextPersistenceFilter.doFilter - Set SecurityContextHolder to empty SecurityContext
2022-10-01 16:16:54.922 DEBUG 1 --- , [http-nio-8080-exec-8] o.s.s.w.c.HttpSessionSecurityContextRepository.saveContext - Did not store empty SecurityContext
2022-10-01 16:16:54.922 DEBUG 1 --- , [http-nio-8080-exec-8] o.s.s.w.c.SecurityContextPersistenceFilter.doFilter - Cleared SecurityContextHolder to complete request
So, my question is why am I getting 401 Unathorized code without configure any SecurityContextPersistenceFilter and any persisten configuration explicitly and BearerTokenAuthenticationFilter is not executed to Authenticate mu request?

Related

CSRF on spring cloud gateway removing formData from POST requests 400 bad request error

I have enabled CSRF on my spring cloud api gateway server.
I have angular as my GUI framework which calls the rest services through the api gateway.
I have used a custom filter to add the CSRF token to the response headers.
When the POST call is made I see that the formData is lost. So I always get 400 Bad request errors.
I disabled CSRF and the request goes through fine without any issues.
Is there something wrong?
Below is my spring cloud gateway configuration. Gateway is used only for routing the requests to other microservices, it does not have any controllers or rest endpoints.
#SpringBootApplication
public class GatewayApplication {
#Autowired
ProfileManager profileManager;
#PostConstruct
public void onInit() {
profileManager.printActiveProfiles();
}
public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); }
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http.authorizeExchange().anyExchange().permitAll();
http.csrf().csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse());
return http.build();
}
}
below is the filter code
#Component
public class CsrfHeaderFilter implements WebFilter {
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<CsrfToken> token = (Mono<CsrfToken>) exchange.getAttributes().get(CsrfToken.class.getName());
if (token != null) {
return token.flatMap(t -> chain.filter(exchange));
}
return chain.filter(exchange);
}
}
My POST rest endpoints are defined with
#RequestParam
below is the code from one of the rest service endpoints. It is an upstream service implemented using the traditional servlet springboot framework.
#RequestMapping(value = "terminate/{listName}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED)
#CrossOrigin
#Loggable (activityname = ActivityLogConstants.DESCRIPTOR_TERMINATE)
public Response terminate(#Context HttpServletRequest reqContext, #PathVariable String listName, #RequestParam(value = "rowData") String rowData)
throws ServiceException {....}
The formData is lost by the time the request reaches the upstream services.
Looks like the filter in spring cloud gateways is blocking formData
here is my netty configuration:
#Configuration
public class NettyConfiguration implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
#Value("${server.max-initial-line-length:65536}")
private int maxInitialLingLength;
#Value("${server.max-http-header-size:65536}")
private int maxHttpHeaderSize;
public void customize(NettyReactiveWebServerFactory container) {
container.addServerCustomizers(
httpServer -> httpServer.httpRequestDecoder(
httpRequestDecoderSpec -> {
httpRequestDecoderSpec.maxHeaderSize(maxHttpHeaderSize);
httpRequestDecoderSpec.maxInitialLineLength(maxInitialLingLength);
return httpRequestDecoderSpec;
}
)
);
}
}
below is my application.yml
sample log:
2022-07-28 09:18:20.743 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.client.HttpClientOperations : [id:199cd714-5, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] Received response (auto-read:false) : [X-Content-Type-Options=nosniff, X-XSS-Protection=1; mode=block, Cache-Control=no-cache, no-store, max-age=0, must-revalidate, Pragma=no-cache, Expires=0, Strict-Transport-Security=max-age=31536000 ; includeSubDomains, X-Frame-Options=DENY, X-Application-Context=application:18080, Date=Thu, 28 Jul 2022 03:48:20 GMT, Connection=close, content-length=0]
2022-07-28 09:18:20.744 DEBUG 26532 --- [ctor-http-nio-5] r.n.r.DefaultPooledConnectionProvider : [id:199cd714-5, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] onStateChange(POST{uri=/cms-service/webapi/terminate/descriptor, connection=PooledConnection{channel=[id: 0x199cd714, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080]}}, [response_received])
2022-07-28 09:18:20.744 DEBUG 26532 --- [ctor-http-nio-5] reactor.netty.channel.FluxReceive : [id:199cd714-5, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] FluxReceive{pending=0, cancelled=false, inboundDone=false, inboundError=null}: subscribing inbound receiver
2022-07-28 09:18:20.744 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.client.HttpClientOperations : [id:199cd714-5, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] Received last HTTP packet
2022-07-28 09:18:20.744 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.server.HttpServerOperations : [id:b0f975eb-11, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Decreasing pending responses, now 0
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.server.HttpServerOperations : [id:b0f975eb-11, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Last HTTP packet was sent, terminating the channel
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [b0f975eb-11, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Completed 400 BAD_REQUEST
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.server.HttpServerOperations : [id:b0f975eb-11, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Last HTTP response frame
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] c.m.webgateway.handler.RequestLogger : Total time required to process /cms-service/webapi/terminate/descriptor request 60055
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] r.n.r.DefaultPooledConnectionProvider : [id:199cd714, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] onStateChange(POST{uri=/cms-service/webapi/terminate/descriptor, connection=PooledConnection{channel=[id: 0x199cd714, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080]}}, [response_completed])
2022-07-28 09:18:20.745 DEBUG 26532 --- [ctor-http-nio-5] r.n.r.DefaultPooledConnectionProvider : [id:199cd714, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080] onStateChange(POST{uri=/cms-service/webapi/terminate/descriptor, connection=PooledConnection{channel=[id: 0x199cd714, L:/127.0.0.1:50342 - R:localhost/127.0.0.1:18080]}}, [disconnecting])
2022-07-28 09:18:20.752 DEBUG 26532 --- [ctor-http-nio-5] r.n.resources.PooledConnectionProvider : [id:199cd714, L:/127.0.0.1:50342 ! R:localhost/127.0.0.1:18080] Channel closed, now: 0 active connections, 4 inactive connections and 0 pending acquire requests.
2022-07-28 09:18:20.752 DEBUG 26532 --- [ctor-http-nio-5] r.n.r.DefaultPooledConnectionProvider : [id:199cd714, L:/127.0.0.1:50342 ! R:localhost/127.0.0.1:18080] onStateChange(PooledConnection{channel=[id: 0x199cd714, L:/127.0.0.1:50342 ! R:localhost/127.0.0.1:18080]}, [disconnecting])
2022-07-28 09:18:23.805 DEBUG 26532 --- [ctor-http-nio-5] r.n.http.server.HttpServerOperations : [id:b0f975eb, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Increasing pending responses, now 1
2022-07-28 09:18:23.805 DEBUG 26532 --- [ctor-http-nio-5] reactor.netty.http.server.HttpServer : [id:b0f975eb-12, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] Handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter#7c82616c
2022-07-28 09:18:23.805 DEBUG 26532 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [b0f975eb-12, L:/0:0:0:0:0:0:0:1:10443 - R:/0:0:0:0:0:0:0:1:50337] HTTP GET "/cms-service/webapi/data/descriptor"
below is the link to the sample project.
https://github.com/manjosh1990/webgateway-issues
I tried to ignore FORM URL ENCODED requests and GET request, but it still does not work
private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>(
Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS));
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange().anyExchange().permitAll().and()
.csrf(csrf -> csrf
.requireCsrfProtectionMatcher(ignoringFormUrlEncodedContentType())
.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()));
return http.build();
}
private ServerWebExchangeMatcher ignoringFormUrlEncodedContentType() {
return (exchange) -> !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(
exchange.getRequest().getHeaders().getContentType()) || !ALLOWED_METHODS.contains(exchange.getRequest().getMethod())
? ServerWebExchangeMatcher.MatchResult.match()
: ServerWebExchangeMatcher.MatchResult.notMatch();
}
Thanks for the minimal sample to reproduce the issue!
After some testing, I'm unable to come up with a workaround or fix for your configuration that allows a form post (URL-encoded) to pass through the gateway with CSRF protection enabled. My best guess is it has to do with how Spring Security is consuming the request body (which should be cached for subsequent filters to consume) vs how Spring Cloud Gateway is consuming the request body in order to proxy to the downstream service.
I tested this by disabling CSRF protection and adding the following filter:
#Component
public class TestWebFilter implements WebFilter {
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Mono.defer(() -> exchange.getFormData()
.doOnSuccess(System.out::println))
.then(chain.filter(exchange));
}
}
In my testing, this causes the request through the gateway to block for a long time before receiving:
{
"timestamp": "2022-08-10T19:13:54.265+00:00",
"status": 400,
"error": "Bad Request",
"path": "/cms-service/webapi/service/post/test"
}
Since this appears to be a bug in Spring Security, I'd recommend submitting a bug in Spring Security and we can work through it from there.
If you would like to work around the issue in the meantime, you can disable CSRF protection for these types of requests, as follows:
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange((authorize) -> authorize
.anyExchange().authenticated()
)
.csrf((csrf) -> csrf
.requireCsrfProtectionMatcher(ignoringFormUrlEncodedContentType())
.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())
)
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
return http.build();
}
private ServerWebExchangeMatcher ignoringFormUrlEncodedContentType() {
return (exchange) -> !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(
exchange.getRequest().getHeaders().getContentType())
? ServerWebExchangeMatcher.MatchResult.match()
: ServerWebExchangeMatcher.MatchResult.notMatch();
}
}
Important: This is not ideal, because these requests won't be protected. However, this might make sense if these requests were never performed in a browser. In that case, it would make sense to have a separate authentication mechanism, such as requiring a bearer token instead of form login, etc. (as in the example above).

spring webflux - don't create session for specific paths

My spring webflux service exposes a health-check endpoint, which is called every few seconds. spring-security is configured, and currently each health-check call creates a new session, which fills the SessionStore quickly.
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.pathMatchers("/actuator/*").permitAll() // disable security for health-check
.anyExchange().authenticated()
...
.and().build();
}
logs:
2020-07-23 21:58:03.805 DEBUG 4722 --- [ctor-http-nio-3] o.s.w.s.adapter.HttpWebHandlerAdapter : [b185e815-1] HTTP GET "/actuator/health"
2020-07-23 21:58:03.845 DEBUG 4722 --- [ctor-http-nio-3] o.s.w.s.s.DefaultWebSessionManager : Created new WebSession.
Is it possible to configure spring-session or spring-security to not create sessions for specific paths?

Spring boot client fails to register Spring boot admin (version 2.x)

I am running spring boot application with basic authentication enabled and spring boot admin with UI security enabled .
My spring boot client fails to register to the spring boot admin server . Below are the logs :
2018-08-23 15:17:09.676 DEBUG 4992 --- [gistrationTask1] o.s.web.client.RestTemplate : Created POST request for "http://localhost:9001/instances"
2018-08-23 15:17:09.699 DEBUG 4992 --- [gistrationTask1] o.s.web.client.RestTemplate : Setting request Accept header to [application/json, application/*+json]
2018-08-23 15:17:09.724 DEBUG 4992 --- [gistrationTask1] o.s.web.client.RestTemplate : Writing [Application(name=spring-boot-application, managementUrl=http://localhost:8001/relay/actuator, healthUrl=http://localhost:8001/relay/actuator/health, serviceUrl=http://localhost:8001/relay)] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#12c0c0b3]
2018-08-23 15:17:09.864 DEBUG 4992 --- [gistrationTask1] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#5953ec3b8 pairs: {POST /instances HTTP/1.1: null}{Accept: application/json}{Content-Type: application/json}{Authorization: Basic YWRtaW46YWRtaW4=}{User-Agent: Java/1.8.0_161}{Host: localhost:9001}{Connection: keep-alive}{Content-Length: 287}
2018-08-23 15:17:10.124 DEBUG 4992 --- [gistrationTask1] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#126c0bea10 pairs: {null: HTTP/1.1 403}{Cache-Control: no-cache, no-store, max-age=0, must-revalidate}{Pragma: no-cache}{Expires: 0}{X-Content-Type-Options: nosniff}{X-Frame-Options: DENY}{X-XSS-Protection: 1 ; mode=block}{Content-Type: text/plain}{Transfer-Encoding: chunked}{Date: Thu, 23 Aug 2018 09:47:10 GMT}
2018-08-23 15:17:10.128 DEBUG 4992 --- [gistrationTask1] o.s.web.client.RestTemplate : POST request for "http://localhost:9001/instances" resulted in 403 (null); invoking error handler
2018-08-23 15:17:10.138 WARN 4992 --- [gistrationTask1] d.c.b.a.c.r.ApplicationRegistrator : Failed to register application as Application(name=spring-boot-application, managementUrl=http://localhost:8001/relay/actuator, healthUrl=http://localhost:8001/relay/actuator/health, serviceUrl=http://localhost:8001/relay) at spring-boot-admin ([http://localhost:9001/instances]): 403 null. Further attempts are logged on DEBUG level
Below are my webSecurity config class from admin server
#SpringBootApplication
#EnableAdminServer
#EnableAutoConfiguration
#Configuration
public class SpringStarterAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringStarterAdminApplication.class, args);
}
// Added for spring boot security login ui for admin
public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeRequests()
.antMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
.logout().logoutUrl(adminContextPath + "/logout").and()
.httpBasic().and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers(
"/instances",
"/actuator/**"
);
// #formatter:on
}
}
Not sure what is preventing the client to register to admin Server .
The inner configuration class should be annotated with #Configuration too.
It's even better if you refactor it into a separate class.

Spring Boot with WSO2 OAuth2 - logoutSuccessUrl is not working

We are implementing the service using Spring Boot (1.2.2) with WSO2 IS (5.x) as OAuth2 Identity provider.
As part of logout we wanted to run some cleaning activities and then redirect to login page. Following is the Spring Security Configuration class
#Configuration
#EnableWebMvcSecurity
public class SecurityConfiguration extends OAuth2SsoConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Autowired
private OAuth2ClientContext oAuth2ClientContext;
#Autowired
private MmaLogoutHandler logoutHandler;
#Override
public void match(RequestMatchers matchers) {
matchers.anyRequest();
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logoff", "GET"))
.logoutSuccessUrl("/#/home")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID","remember-me")
.permitAll()
.and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.addFilterBefore(customerAuthorizationFilter(), AbstractPreAuthenticatedProcessingFilter.class);
}
When the logout is called, the log shows that spring security has cleared the session, but it fails to redirect -
2015-09-01 14:23:05.983 DEBUG 12936 --- [nio-8443-exec-8] o.s.s.w.a.logout.LogoutFilter : Logging out user 'org.springframework.security.oauth2.provider.OAuth2Authentication#e6269aa6: Principal: mrpink_bd3d5b71-b212-11e4-ac24-22000b4791d2; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=127.0.0.1, sessionId=<SESSION>, tokenType=bearertokenValue=<TOKEN>; Granted Authorities: ROLE_USER' and transferring to logout destination
2015-09-01 14:23:05.984 DEBUG 12936 --- [nio-8443-exec-8] o.s.s.w.a.l.SecurityContextLogoutHandler : Invalidating session: B7B50DC106F50EDA84ACFEF229DE167B
2015-09-01 14:23:05.984 DEBUG 12936 --- [nio-8443-exec-8] .s.s.w.a.l.SimpleUrlLogoutSuccessHandler : Using default Url: /#/home
2015-09-01 14:23:05.984 DEBUG 12936 --- [nio-8443-exec-8] .s.s.w.a.l.SimpleUrlLogoutSuccessHandler : Response has already been committed. Unable to redirect to /#/home
2015-09-01 14:23:05.984 DEBUG 12936 --- [nio-8443-exec-8] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
As per log the redirection fails and the page is not actually redirected.
Is this due to OAuth2 or there is already default log out handler with Spring boot that is needed to be overridden?

How do I enable logging for Spring Security?

I am setting up Spring Security to handle logging users in. I have logged in as a user, and am taken to an Access Denied error page upon successful login. I don't know what roles my user has actually been assigned, or the rule that causes access to be denied, because I can't figure out how to enable debugging for the Spring Security library.
My security xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ... >
<!-- security -->
<security:debug/><!-- doesn't seem to be working -->
<security:http auto-config="true">
<security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
<security:form-login login-page="/Load.do"
default-target-url="/Admin.do?m=loadAdminMain"
authentication-failure-url="/Load.do?error=true"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"/>
<security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="loginDataSource"
users-by-username-query="SELECT username, password, active FROM userinformation WHERE username = ?"
authorities-by-username-query="
SELECT ui.username, r.rolename
FROM role r, userrole ur, userinformation ui
WHERE ui.username=?
AND ui.userinformationid = ur.userinformationid
AND ur.roleid = r.roleid "
/>
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
</beans>
I've also tried adding log4j.logger.org.springframework.security=DEBUG to my log4j.properties
How can I get debug output for Spring Security?
Assuming you're using Spring Boot, another option is to put the following in your application.properties:
logging.level.org.springframework.security=DEBUG
This is the same for most other Spring modules as well.
If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.
Here is the application.yml version as well:
logging:
level:
org:
springframework:
security: DEBUG
You can easily enable debugging support using an option for the #EnableWebSecurity annotation:
#EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
Basic debugging using Spring's DebugFilter can be configured like this:
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.debug(true);
}
}
You can easily enable debugging support using an option for the #EnableWebSecurity annotation:
#EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
If you need profile-specific control the in your application-{profile}.properties file
org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false
Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/
We can always check the registered filters inside Spring Security with the below configuration
#EnableWebSecurity(debug=true) - We need to enable the debugging of the security details
Enable logging of the details by adding the below property in the application.properties logging.level.org.springframework.security.web.FilterChainProxy=DEBUG
Below mentioning some of the internal filters of Spring Security that gets executed in the authentication flow:
Security filter chain: [
CharacterEncodingFilter
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
X509AuthenticationFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
RememberMeAuthenticationFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
Using Spring Boot with default spring security filters (without customizing anything, and without even setting debug in the EnableWebSecurity annotation), setting TRACE as the following application.properties shows:
logging.level.org.springframework.security=TRACE
Is enough for it to show in detail what filters are being called and what they are doing.
TRACE w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
TRACE w.c.HttpSessionSecurityContextRepository : Created SecurityContextImpl [Null authentication]
DEBUG w.c.HttpSessionSecurityContextRepository : Created HttpSession as SecurityContext is non-default
...
DEBUG o.s.security.web.FilterChainProxy : Securing POST /api/product/productname01
TRACE o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (1/16)
...
TRACE o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/16)
DEBUG o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost/api/product/productname01
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code
Versions:
Spring Framework Bom version 5.3.16
Spring Boot 2.6.4
Spring 5.3.16
Spring Security 5.6.2
Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by #bzhu in comment How do I enable logging for Spring Security?)
Until this gets into a GA release, here is how to get this milestone release in gradle
repositories {
mavenCentral()
if (!version.endsWith('RELEASE')) {
maven { url "https://repo.spring.io/milestone" }
}
}
// Force earlier milestone release to get securing logging preview
// https://docs.spring.io/spring-security/site/docs/current/reference/html5/#getting-gradle-boot
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
You have two options:
1. Set the logging level of Spring Security to debug or trace:
application.yml:
logging:
level:
org:
springframework:
security: debug # or trace
application.properties:
logging.level.org.springframework.security=debug
2. Enable the Spring Security debug mode
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.debug(true);
}
}
or like this:
#Configuration
#EnableWebSecurity(debug = true)
public class SecurityConfig {
}

Resources