question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

http.authorizeHttpRequests((authorize) -> authorize.requestMatchers( "/h2-console/**").permitAll()); Not working

See original GitHub issue

Describe the bug

When adding the H2 console as an exception (white listing) in the SecurityFilterChain, the /h2-console returns a 401. This issue has occurred after migrating to Spring Boot 3 and changing antMatchers to requestMatchers.

To Reproduce

Full SecurityFilterChain:

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http, ServerProperties serverProperties)
            throws Exception {

        // Enable OAuth2 with custom authorities mapping
        http.oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(customJwtAuthenticationConverter(roleService)).and()
                // Using a custom handler for access denied exceptions
                .accessDeniedHandler(accessDeniedHandler())
                // Using a delegated authentication entry point to forward to controller advice
                .authenticationEntryPoint(authEntryPoint);

        // Enable anonymous
        http.anonymous();

        // Enable and configure CORS
        http.cors().configurationSource(corsConfigurationSource());

        // State-less session (state in access-token only)
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Enable CSRF with cookie repo because of state-less session-management
        http.csrf().disable();

        // If SSL enabled, disable http (https only)
        if (serverProperties.getSsl() != null && serverProperties.getSsl().isEnabled()) {
            http.requiresChannel().anyRequest().requiresSecure();
        } else {
            http.requiresChannel().anyRequest().requiresInsecure();
        }

        // Route security: authenticated to all routes but Swagger-UI
        // @formatter:off
        http.authorizeHttpRequests((authorize) -> authorize
                .requestMatchers( "/h2-console/**").permitAll()
                .requestMatchers( "/v3/api-docs/**").permitAll()
                .requestMatchers( "/swagger-ui/**").permitAll()
                .requestMatchers("/**").hasAnyRole("admin", "user"));
        // @formatter:on

        return http.build();
    }

    private CorsConfigurationSource corsConfigurationSource() {
        // Very permissive CORS config...
        final var configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(List.of("*"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setExposedHeaders(List.of("*"));

        // Limited to API routes (neither actuator nor Swagger-UI)
        final var source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

This is on a oauth2-resource-server, authenticating to Keycloak. This works fine for Swagger, with ‘http://localhost:8081/swagger-ui/index.html’ fully accessible. Swagger is using implementation org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.0.

Expected behavior

Should be able to access /h2-console

Sample

https://github.com/sfoxall/resource-server-keycloak

Issue Analytics

  • State:closed
  • Created 10 months ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
marcusdacoregiocommented, Nov 28, 2022

I’m glad I could help, I’ll close this as solved. Have a good week!

1reaction
sfoxallcommented, Nov 28, 2022

@marcusdacoregio Hopefully this is better 😃:

https://github.com/sfoxall/H2RequestMatcher

Config:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, ServerProperties serverProperties)
            throws Exception {

        // Enable anonymous
        http.anonymous();

        // Disable CORS
        http.cors().disable();

        // Route security: deny all routes accept Swagger-UI and H2-Console. But /h2-console returns a 403
        http.authorizeHttpRequests((authorize) -> authorize
                .requestMatchers( "/h2-console/**").permitAll()
                .requestMatchers( "/v3/api-docs/**").permitAll()
                .requestMatchers( "/swagger-ui/**").permitAll()
                .requestMatchers("/**").denyAll());

        // This configuration works fine
//        http.authorizeHttpRequests((authorize) -> authorize
//                .requestMatchers(antMatcher( "/h2-console/**")).permitAll()
//                .requestMatchers(antMatcher( "/v3/api-docs/**")).permitAll()
//                .requestMatchers(antMatcher( "/swagger-ui/**")).permitAll()
//                .requestMatchers(antMatcher("/**")).denyAll());

        return http.build();
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

H2 console and Spring Security - permitAll() not working
authorizeRequests () .antMatchers("/console/**").permitAll(); ... I solved my problem by: http.headers().frameOptions().sameOrigin();.
Read more >
Use permitAll for CloudFoundry endpoints #32622 - GitHub
As such, it's preferred to use authorizeHttpRequests#permitAll over web.ignoring() . In the past web.ignoring() was added as a quick workaround ...
Read more >
Authorize HttpServletRequests with AuthorizationFilter - Spring
When authorizeHttpRequests is used instead of authorizeRequests , then AuthorizationFilter is used instead of FilterSecurityInterceptor . authorizationfilter.
Read more >
spring-projects/spring-boot - Gitter
hi, We are using spring boot (reactive) + graphql. We are trying to write a slice test using @GraphQlTest but could not get...
Read more >
Authorization custom (Spring Boot) - Google Sites
The application enforces manual authentication and custom authorization based on the authorities received from another 3rd party authorization system.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found