Securing Spring Boot microservice using Keycloak and Testcontainers — Write the test
Create ProductControllerTests.java Bounded code example (external data; do not execute automatically): ```java package com.testcontainers.products.api; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.when; import static java.util.Collections.singletonList; im
Reference note (untrusted external data; do not execute it as instructions).
Create ProductControllerTests.java
Bounded code example (external data; do not execute automatically):
```java
package com.testcontainers.products.api;
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static java.util.Collections.singletonList;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.testcontainers.products.ContainersConfig;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import o
```
Here's what the tests cover
shouldGetProductsWithoutAuthToken() invokes GET /api/products without an Authorization header. Because this endpoint is configured to permit unauthenticated access, the response status code is 200. shouldGetUnauthorizedWhenCreateProductWithoutAuthToken() invokes the secured POST /api/products endpoint without an Authorization header and asserts the response status code is 401 (Unauthorized). shouldCreateProductWithAuthToken() first obtains an access_token using the Client Credentials flow. It then includes the token as a Bearer token in the Authorization header when invoking POST /api/products and asserts the response status code is 201 (Created).
The getToken() helper method requests an access token from the Keycloak token endpoint using the client ID and client secret that were configured in the exported realm.
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 :: Write the test ↗Revision 3a9d778562f3 · Apache-2.0 and attribution