Test With Real OAuth 2.0 Tokens From Keycloak and Testcontainers
Run Keycloak in Docker with Testcontainers, discover its endpoints with OpenID Connect discovery, get real access tokens with the client credentials grant, and test an API that verifies them against Keycloak's published keys.
Module 7 and Module 11 minted their own tokens, with keys the tests controlled. That tests the API’s rules well, but leaves one question open: does the API work with the tokens a real authorization server issues? Real servers have their own ideas about which claim holds the client, whether the audience is a string or a list, and which error code a failed login gets. The only way to find out is to run a real one. In this guide, you’ll start Keycloak in Docker from a test class, get real tokens from it, and send them to an API that verifies them against Keycloak’s published keys.
Level: Advanced · Time: 30 minutes · Part of: Module 12: Real Infrastructure with Testcontainers, section 1
What You’ll Build
You’ll build a test class called KeycloakTokensTest with five tests. Three send real Keycloak tokens to a protected accounts API: a reader, a payer, and a reader who tries to pay. One proves Keycloak refuses a wrong secret, and one reads the claims Keycloak puts in a token.
The chain under test:
1
2
3
test --REST Assured--> Keycloak (token endpoint) client credentials -> access token
test --REST Assured--> ProtectedAccountsApi Authorization: Bearer <token>
ProtectedAccountsApi --> Keycloak fetch signing keys (JWKS)
When you’re done, Maven reports five passing tests, in about eleven seconds:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Start Keycloak.
- Use real tokens.
- Read what Keycloak puts in a token.
What You Need
- About 30 minutes
- JDK 26 or later
- Maven 3.9 or later
- Docker, running
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can get a token with the client credentials grant, as taught in Get and Send OAuth 2.0 Bearer Tokens in REST Assured, and you know how a resource server verifies a JWT, from Test Spring Boot on a Random Port With REST Assured and Real Tokens.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: this is the first section of Module 12, so you start from scratch. Create
KeycloakTokensTestin themodule-12test sources and follow every heading below. - Skip ahead: open the finished class (
KeycloakTokensTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: clone the examples repository and change into it:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
If you’ve already cloned it for an earlier module, run git pull instead. The module uses Testcontainers 2.0 and testcontainers-keycloak 4.4, with the Keycloak 26.8.2 image. The first run downloads the image, which takes a while.
Out of scope: this guide uses the client credentials grant only. It doesn’t cover user logins, refresh tokens or configuring Keycloak beyond the imported realm.
Understand Testcontainers and Keycloak
The problem. Self-minted tokens have exactly the shape the test chose. A real authorization server decides the claims, their types and its error codes, and an API built against self-minted tokens can break on the first real one.
The concept. Three pieces work together:
- Testcontainers starts Docker containers from a test, waits until they’re ready, and removes them afterwards. Its JUnit integration does that with
@Testcontainerson the class and@Containeron a field. - Keycloak is an open-source identity and access management server, and a complete OAuth 2.0 and OpenID Connect authorization server. The
KeycloakContainerfromtestcontainers-keycloakruns it. - A realm is Keycloak’s unit of configuration: clients, scopes and users. The test imports one from a JSON file when Keycloak starts.
OpenID Connect discovery then tells the test where everything is: the server publishes its configuration at /.well-known/openid-configuration.
When to use each. Use a real authorization server for a few end-to-end tests that prove the API accepts real tokens and the server is configured as you think. Keep the many rule tests on self-minted tokens or a web slice: a real server costs seconds and Docker.
Test against the real server once, and read what it really sends.
Meet the API Under Test
The realm open-banking-realm.json defines two confidential clients, both with the client credentials grant, and an audience mapper that adds accounts-api to their tokens:
| Client | Secret | May get scopes |
|---|---|---|
tpp-accounts | accounts-secret | accounts:read |
tpp-payments | payments-secret | accounts:read, payments:write |
ProtectedAccountsApi is a resource server. GET /api/v1/accounts needs accounts:read, and answers with the client and its accounts; POST /api/v1/payments needs payments:write, and answers 201 with a paymentId. Its JwksTokenVerifier checks the RS256 signature with the keys Keycloak publishes, matched by the token’s key id (kid), plus the issuer, audience and expiry. When it sees an unknown key id, it reloads the keys, which is how a resource server survives key rotation.
| Request to the API | Answer |
|---|---|
| No token | 401 with WWW-Authenticate: Bearer realm="accounts-api" |
| A token with a broken signature | 401 with error="invalid_token", error_description="The signature is invalid" |
| A token without the scope | 403 with error="insufficient_scope", scope="payments:write" |
Your tests check these values:
- The status of each request, and the API’s
clientandpaymentId. - The
WWW-Authenticateheader of a refusal. - The claims inside a token:
iss,azp,scopeandaud.
Start Keycloak
Set Up the Test Class
Goal: start one Keycloak for the class, with the realm imported.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.javanibble.module_12.section_01;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import com.javanibble.resource.ProtectedAccountsApi;
import dasniko.testcontainers.keycloak.KeycloakContainer;
import io.restassured.path.json.JsonPath;
import io.restassured.specification.RequestSpecification;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Testcontainers(disabledWithoutDocker = true)
@Tag("keycloak")
@Tag("security")
class KeycloakTokensTest {
@Container
static final KeycloakContainer KEYCLOAK = new KeycloakContainer("quay.io/keycloak/keycloak:26.8.2")
.withRealmImportFile("/keycloak/open-banking-realm.json");
private static String issuer;
private static String tokenEndpoint;
private static ProtectedAccountsApi api;
}
What’s happening:
@Testcontainersfinds the@Containerfields and manages them. Astaticcontainer starts once for the class and stops after it.disabledWithoutDocker = trueskips the class on a machine without Docker, instead of failing it, so the rest of the module still runs.withRealmImportFile(..)imports the realm from the test classpath when Keycloak starts.- The tags let a build select or exclude these tests, as section 3 of this module shows.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Make the
@Containerfieldstatic. An instance field gives every test method its own container, so this class would start Keycloak five times, at about ten seconds each.
Discover the Endpoints
Goal: ask Keycloak where its token endpoint and keys are, start the API, and add helpers for tokens and requests.
Add these methods to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@BeforeAll
static void discoverKeycloakAndStartTheApi() {
issuer = KEYCLOAK.getAuthServerUrl() + "/realms/open-banking";
// OpenID Connect discovery: ask the server for its endpoints instead of hard-coding them.
JsonPath discovery = given()
.when().get(issuer + "/.well-known/openid-configuration")
.then().statusCode(200)
.body("issuer", equalTo(issuer))
.body("grant_types_supported", hasItem("client_credentials"))
.extract().jsonPath();
tokenEndpoint = discovery.getString("token_endpoint");
api = ProtectedAccountsApi.start(issuer, discovery.getString("jwks_uri"));
}
@AfterAll
static void stopApi() {
api.close();
}
private static String token(String clientId, String secret, String scope) {
return given()
.auth().preemptive().basic(clientId, secret)
.formParam("grant_type", "client_credentials")
.formParam("scope", scope)
.when()
.post(tokenEndpoint)
.then()
.statusCode(200)
.body("token_type", equalTo("Bearer"))
.extract().path("access_token");
}
private static RequestSpecification api() {
return given().baseUri(api.baseUri()).port(api.port());
}
What’s happening:
getAuthServerUrl()gives Keycloak’s address, with the port Testcontainers mapped to a free one. Discovery returned, in one run:1 2 3
issuer=http://localhost:61383/realms/open-banking token_endpoint=http://localhost:61383/realms/open-banking/protocol/openid-connect/token jwks_uri=http://localhost:61383/realms/open-banking/protocol/openid-connect/certs
- The API starts with the issuer and the JWKS URI, so it trusts exactly this Keycloak.
token(..)is the client credentials request from Module 7, sent to a real server. Keycloak answered{"access_token":"eyJ...","expires_in":300,"refresh_expires_in":0,"token_type":"Bearer","not-before-policy":0,"scope":"payments:write accounts:read"}.
Checkpoint: the class compiles. The port changes on every run, and discovery handles it.
Use Real Tokens
Read Accounts With an Accounts Token
Goal: prove the API accepts a real token with accounts:read.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void anAccountsTokenReadsAccounts() {
api()
.auth().oauth2(token("tpp-accounts", "accounts-secret", "accounts:read"))
.when()
.get("/api/v1/accounts")
.then()
.statusCode(200)
.body("client", equalTo("tpp-accounts"));
}
What’s happening:
- The API fetched Keycloak’s keys from the JWKS URI, verified the signature, and checked the issuer, audience, expiry and scope.
- It read the client from the token, so
clientproves which token it saw.
Checkpoint: run KeycloakTokensTest from your IDE with Docker running. One test runs and passes, after Keycloak starts.
Initiate a Payment With a Payments Token
Goal: prove a real token with payments:write can pay.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void aPaymentsTokenInitiatesPayments() {
api()
.auth().oauth2(token("tpp-payments", "payments-secret", "payments:write"))
.when()
.post("/api/v1/payments")
.then()
.statusCode(201)
.body("paymentId", notNullValue());
}
What’s happening:
tpp-paymentsmay getpayments:write, so Keycloak issues it, and the API answers201with apaymentId, such aspmt-aab7ea48.
Checkpoint: run the class again. Two tests pass, with one Keycloak.
Refuse an Accounts Token for Payments
Goal: prove a real token without payments:write can’t pay.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void anAccountsTokenCannotInitiatePayments() {
api()
.auth().oauth2(token("tpp-accounts", "accounts-secret", "accounts:read"))
.when()
.post("/api/v1/payments")
.then()
.statusCode(403)
.header("WWW-Authenticate", containsString("insufficient_scope"));
}
What’s happening:
- The token is valid, but has only
accounts:read, so the API answers403. - The full header is
Bearer realm="accounts-api", error="insufficient_scope", scope="payments:write", as RFC 6750 requires.
Checkpoint: run the class again. Three tests pass.
Let Keycloak Refuse a Wrong Secret
Goal: prove the real token endpoint refuses a wrong client secret.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void keycloakRejectsAWrongSecret() {
given()
.auth().preemptive().basic("tpp-accounts", "not-the-secret")
.formParam("grant_type", "client_credentials")
.when()
.post(tokenEndpoint)
.then()
.statusCode(401);
}
What’s happening:
- Keycloak answers
401with{"error":"unauthorized_client","error_description":"Invalid client or Invalid client credentials"}. - RFC 6749 names
invalid_clientfor a failed client authentication, which is what Module 7’s test API returned. This is the kind of difference a real server shows, and why the test checks the status, not the error code.
Checkpoint: run the class again. Four tests pass.
Read What Keycloak Puts in a Token
Check the Claims
Goal: decode a real token, and check the claims the API depends on.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void theTokenHasTheExpectedClaims() {
String token = token("tpp-payments", "payments-secret", "accounts:read payments:write");
JsonPath claims = JsonPath.from(new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8));
assertThat(claims.getString("iss"), equalTo(issuer));
assertThat(claims.getString("azp"), equalTo("tpp-payments")); // the client the token was issued to
assertThat(claims.getString("scope"), containsString("payments:write"));
Object aud = claims.get("aud"); // a string, or a list of strings
List<Object> audiences = aud instanceof List<?> list ? new ArrayList<>(list) : List.of(aud);
assertThat(audiences, hasItem("accounts-api"));
}
What’s happening:
- The middle part of a JWT is its claims, Base64URL-encoded.
JsonPath.from(..)reads them. A real token’s claims, from one run:
1 2 3 4
{"exp":1795337592,"iat":1795337292,"jti":"trrtcc:21fd91f8-3d4b-19df-6547-813a16084672", "iss":"http://localhost:61383/realms/open-banking","aud":"accounts-api", "sub":"34964314-be2a-47db-9da8-42e89409e3a2","typ":"Bearer","azp":"tpp-payments", "scope":"payments:write accounts:read"}
- The client is in
azp, the authorized party, not inclient_id;subis the id of the client’s service account. audis a string here, and becomes a list when a token has more than one audience, so the test, like the API’s verifier, accepts both.- The scopes come in Keycloak’s order, not the order asked for, so the test uses
containsString(..).
Checkpoint: run the class again. All five tests pass.
These details are why a test against the real server is worth its seconds: a verifier that read
client_id, or expectedaudto be a list, would have worked with every self-minted token and failed with Keycloak’s.
Run the Tests
Start Docker, then run the following command from the repository root:
1
mvn test -pl module-12 -Dtest=KeycloakTokensTest
You should see a result similar to the following, after Testcontainers’ and Keycloak’s logs:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_12.section_01.KeycloakTokensTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 11.15 s -- in com.javanibble.module_12.section_01.KeycloakTokensTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Most of the eleven seconds is Keycloak’s start-up. Without Docker, disabledWithoutDocker = true reports the five tests as skipped.
Make a Test Fail
In token(..), delete the .formParam("scope", scope) line and run the command again. You should see a result similar to the following:
1
2
3
4
5
6
7
8
9
10
[ERROR] Failures:
[ERROR] KeycloakTokensTest.aPaymentsTokenInitiatesPayments:109 1 expectation failed.
Expected status code <201> but was <403>.
[ERROR] KeycloakTokensTest.anAccountsTokenReadsAccounts:98 1 expectation failed.
Expected status code <200> but was <403>.
[ERROR] KeycloakTokensTest.theTokenHasTheExpectedClaims:142
Expected: a string containing "payments:write"
but: was ""
Without a scope parameter, Keycloak still issued tokens, with "scope":"": the realm lists the scopes as optionalClientScopes, with empty defaultClientScopes, so a client gets them only when it asks. Every token was valid, and none could do anything. A real server’s defaults are part of what you test.
Put the line back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| All five tests skipped | Docker isn’t running | Start Docker |
403 with a valid token | The token was requested without the scope | Send scope with the token request |
400 with invalid_scope from Keycloak | The client may not have that scope | Check the client’s scopes in the realm |
401 with unauthorized_client from Keycloak | A wrong client id or secret | Use the realm’s values |
Connection refused to Keycloak | A hard-coded URL or port | Use getAuthServerUrl() and discovery |
Try It Yourself
Exercise 1: Ask for a Scope the Client May Not Have
Add a test called keycloakRefusesAScopeTheClientMayNotHave. Ask Keycloak for a tpp-accounts token with the scope payments:write, and check that it answers 400 with error equal to invalid_scope.
Hint
Send the request without the token(..) helper, which expects 200. Keycloak’s error_description names the scopes it refused.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void keycloakRefusesAScopeTheClientMayNotHave() {
given()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "client_credentials")
.formParam("scope", "payments:write")
.when()
.post(tokenEndpoint)
.then()
.statusCode(400)
.body("error", equalTo("invalid_scope"))
.body("error_description", equalTo("Invalid scopes: payments:write"));
}
Exercise 2: Send a Token Without Scopes
Add a test called aTokenWithoutScopesCanDoNothing. Get a tpp-accounts token without a scope parameter, check that its scope claim is empty, and that the API refuses it for GET /api/v1/accounts with 403.
Hint
Build the token request yourself, without formParam("scope", ..), and extract access_token. Decode the claims as theTokenHasTheExpectedClaims does.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void aTokenWithoutScopesCanDoNothing() {
String token = given()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "client_credentials")
.when()
.post(tokenEndpoint)
.then()
.statusCode(200)
.extract().path("access_token");
JsonPath claims = JsonPath.from(new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8));
assertThat(claims.getString("scope"), equalTo(""));
api().auth().oauth2(token).when().get("/api/v1/accounts").then().statusCode(403);
}
Summary
You built KeycloakTokensTest, which starts Keycloak in Docker, discovers its endpoints, gets real tokens with the client credentials grant, and proves the accounts API accepts them, refuses the wrong scope, and that Keycloak refuses a wrong secret. You also read what a real token contains.
- Testcontainers starts Keycloak from the test: a
static@Containerfor one per class, a realm imported at start-up, anddisabledWithoutDocker = trueto skip without Docker. - OpenID Connect discovery provides the token endpoint and the JWKS URI, so no URL or port is hard-coded.
- The API verifies real tokens against Keycloak’s published keys, matched by
kid. - Keycloak puts the client in
azp, may sendaudas a string or a list, and answersunauthorized_clientwhere RFC 6749 saysinvalid_client. - Ask for scopes explicitly: a token requested without them is valid and can do nothing.
Here are the commands you used in this guide:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
mvn test -pl module-12 -Dtest=KeycloakTokensTest
What’s Next
Next: continue with Run REST Assured Tests in Parallel With JUnit, which runs independent tests at the same time with JUnit’s parallel execution.
The code:
- The finished test class:
KeycloakTokensTest.java - The realm:
open-banking-realm.json - The code and run commands for this module: Module 12 README
Go deeper:
- testcontainers-keycloak, for
KeycloakContainerand its options. - OpenID Connect Discovery 1.0, for what
/.well-known/openid-configurationcontains. - RFC 6749, section 5.2, for the token endpoint’s error codes.
Related guides:
- Get and Send OAuth 2.0 Bearer Tokens in REST Assured, for the client credentials grant against a test server.
- Test Spring Boot on a Random Port With REST Assured and Real Tokens, for self-minted tokens and their limits.
