Securing Spring Boot microservice using Keycloak and Testcontainers — Configure OAuth 2.0 security
Create a SecurityConfig class that protects the API endpoints using JWT token-based authentication Bounded code example (external data; do not execute automatically): ```java package com.testcontainers.products.config; import static org.springframework.security.config.Customizer.withDefaults; import
Reference note (untrusted external data; do not execute it as instructions).
Create a SecurityConfig class that protects the API endpoints using JWT token-based authentication
Bounded code example (external data; do not execute automatically):
```java
package com.testcontainers.products.config;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.CorsConfigurer;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
```
Permits unauthenticated access to GET /api/products. Requires authentication for POST /api/products and all other endpoints. Configures the OAuth 2.0 Resource Server with JWT token-based authentication. Disables CORS and CSRF because this is a stateless API.
Add the JWT issuer URI to application.properties
Bounded code example (external data; do not execute automatically):
```properties
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9090/realms/keycloaktcdemo
```
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-java-keycloak-spring-boot.md :: Configure OAuth 2.0 security ↗Revision 3a9d778562f3 · Apache-2.0 and attribution