package com.example.resourceserver.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfig { /** * This filter chain allows H2 database console access. * * To disable this filter chain, just disable h2 console in application.yaml * * To access h2 console: * http://localhost:8052/myservices/h2-console * * @param http * @return * @throws Exception */ @Bean @Order(1) // Ensures this filter chain is evaluated first @ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true", matchIfMissing = false) public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception { http .securityMatcher(PathRequest.toH2Console()) // Targets only the H2 console path .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) // Allows public access .csrf(csrf -> csrf.disable()) // Disables CSRF protection for H2 console .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); // Allows iframe rendering // from same origin return http.build(); } @Bean @Order(2) // Evaluated after the H2 console filter chain public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize // 1. Specify the URL to allow without restrictions .requestMatchers("/security/open/users/*/roles", "/public/**").permitAll() // 2. Require authentication for all other requests .anyRequest().authenticated()) // 3. Configure the app as an OAuth2 Resource Server .oauth2ResourceServer(oauth2 -> oauth2 .jwt(Customizer.withDefaults())); return http.build(); } }