147

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?

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
Mar
  • 7,765
  • 9
  • 48
  • 82
  • 2
    check this [link](http://stackoverflow.com/questions/7840088/debugging-spring-configuration) If this can help you. – pise Jun 16 '15 at 16:00
  • 1
    @pise can you add that as an answer (with at least a relevant excerpt/summary) so I can mark this as solved? – Mar Aug 04 '15 at 18:41
  • See the answer to this question : http://stackoverflow.com/questions/7840088/debugging-spring-configuration – nevster May 30 '16 at 05:34
  • Heh - tried to add it as an answer and SO converted it to a comment. – nevster May 30 '16 at 05:35

9 Answers9

260

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
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
delucasvb
  • 5,393
  • 4
  • 25
  • 35
  • 2
    Does this assume Spring Boot? – John Camerin Apr 11 '19 at 14:11
  • 1
    @JohnCamerin Yes, it does. Setting the log levels in `application.properties` is a Spring Boot feature. If you don't use Spring Boot you can set the log level `org.springframework.security` by other means (e.g. in your logback.xml). – Dario Seidl May 07 '19 at 14:02
  • 3
    For WebFlux it is not working: https://github.com/spring-projects/spring-security/issues/5758 – bzhu Oct 22 '19 at 02:06
  • 1
    Add `org.springframework.web.cors` to enable Cors processor logs. – Siggen Jul 07 '20 at 09:28
94

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
27

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);
    }
}
Chris Suszyński
  • 1,494
  • 17
  • 23
  • 20
    That's some pretty weak debug logging. It only prints out the request headers and "Security filter chain". Not useful at all when tracking down access problems. – Chloe May 27 '18 at 02:18
8

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/

Ankit Katiyar
  • 2,631
  • 2
  • 20
  • 30
6

We can always check the registered filters inside Spring Security with the below configuration

  1. @EnableWebSecurity(debug=true) - We need to enable the debugging of the security details
  2. 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
]
sarath
  • 767
  • 12
  • 19
6

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
Tonsic
  • 890
  • 11
  • 15
1

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

}
Guillaume Berche
  • 3,049
  • 2
  • 17
  • 18
0

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 {

}
times29
  • 2,782
  • 2
  • 21
  • 40
0

Put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

To know the roles of the user you can use the following code

@RestController
public class DemoController {
    //....
@GetMapping("/roles")
    public List<String> getUserRoles() {
        List<String> roles = rolesUser();
        return roles;
    }

    private List<String> rolesUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities();
        List<String> roles = authorities.stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList());
        return roles;
    }
}