Post

Test Spring Boot on a Random Port With REST Assured and Real Tokens

Start the whole Spring Boot application on a free port with @SpringBootTest(webEnvironment = RANDOM_PORT), test it over real HTTP with plain REST Assured, and send real signed JWTs so signature, expiry, audience and scope are all checked.

Test Spring Boot on a Random Port With REST Assured and Real Tokens

The web slice tested the security rules with a stand-in for the token. That leaves a gap: is the token itself checked? Does the service reject a token that has expired, one with a forged signature, or one issued for another API? And does the application behave the same with a real servlet container and real HTTP headers as it does under MockMvc? Only one kind of test answers that: the whole application, on a real port, with real signed tokens. In this guide, you’ll start the application, mint tokens with a test key, and find out which token checks your tests really prove.

Level: Advanced · Time: 30 minutes · Part of: Module 11: Spring Boot Integration, section 3

What You’ll Build

You’ll build a test class called RandomPortServerTest with six tests against the running accounts service: a reader lists accounts, a writer opens one that a reader reads back, and three tokens are refused, for expiry, audience and scope. The last test checks a problem detail over HTTP.

A token for another API is refused with a reason:

1
2
3
4
5
GET /api/v1/accounts HTTP/1.1
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: The aud claim is not valid", ...

When you’re done, Maven reports six passing tests:

1
2
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Start the whole application.
  • Test with real signed tokens.
  • Prove each token check is wired in.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create RandomPortServerTest in a new section_03 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (RandomPortServerTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Test a Spring Controller With RestAssuredMockMvc in Standalone Mode.

Out of scope: this guide mints tokens with a test key. Getting real tokens from a real authorization server is taught in Test With Real OAuth 2.0 Tokens From Keycloak and Testcontainers.

Understand Random-Port Tests

The problem. A stand-in token skips decoding, so a web slice can’t prove that the service checks a token’s signature, expiry or audience. Those checks are configuration, and configuration can be wrong or missing without any rule test noticing.

The concept. @SpringBootTest(webEnvironment = RANDOM_PORT) starts the whole application, with an embedded Tomcat on a free port. Every bean is created, as in production, and requests go over the network, through the servlet container and every filter, converter and error handler. @LocalServerPort injects the chosen port; in Spring Boot 4, it lives in org.springframework.boot.test.web.server. The test uses plain REST Assured: to it, this is an HTTP server on localhost.

StyleStartsTestsUse for
Standalone MockMvcThe controllerRouting, JSON, validationMany quick controller tests
Web sliceThe web layer and securityAuthorisation rules, error formatThe rules, without tokens
Random portThe whole applicationEverything, over real HTTPToken validation, end-to-end behaviour

When to use each. A good suite uses all three: many fast tests at the bottom, and a few complete ones at the top. Put every token check in the random-port tests, and make sure each test fails when its check is missing.

A negative token test must fail when the check it’s about is removed.

Meet the API Under Test

The whole accounts service runs, with the security from the web slice and its JwtDecoder. The decoder verifies RS256 JWTs with the public key in src/main/resources/jwt, and applies two validators:

  • JwtValidators.createDefault(), which checks the token’s time claims: it must not have expired, with 60 seconds of clock skew allowed.
  • A JwtClaimValidator for aud, which must contain accounts-api.

Every refused token gets 401, with the reason in WWW-Authenticate:

Tokenerror_description ends with
None(no error; Bearer resource_metadata=.. only)
A forged signatureSigned JWT rejected: Invalid signature
Expired five minutes agoJwt expired at 2026-11-22T08:32:22Z
Issued for payments-apiThe aud claim is not valid
exp earlier than iatexpiresAt must be after issuedAt

Your tests check these values:

  • The status, and the reason in WWW-Authenticate.
  • The accounts’ ids and owner, and the Location of a new one.
  • The problem detail for an unknown account.

Start the Whole Application

Meet TestTokens

Goal: see how the tests get real signed tokens without an authorization server.

The module’s support package already contains TestTokens, which signs tokens with the test key in src/test/resources/jwt, matching the service’s public key:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static final String AUDIENCE = "accounts-api";

public static String withScopes(String... scopes) {
    return token(List.of(scopes), AUDIENCE, Duration.ofMinutes(5));
}

public static String token(List<String> scopes, String audience, Duration lifetime) {
    Instant now = Instant.now();
    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claims = """
        {"iss":"https://auth.example.com","sub":"tpp-client","aud":"%s","scope":"%s","iat":%d,"exp":%d}"""
        .formatted(audience, String.join(" ", scopes), now.getEpochSecond(), now.plus(lifetime).getEpochSecond());
    String signingInput = encode(header) + "." + encode(claims);
    try {
        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initSign(KEY);
        signer.update(signingInput.getBytes(StandardCharsets.US_ASCII));
        return signingInput + "." + BASE64URL.encodeToString(signer.sign());
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

What’s happening:

  • withScopes(..) gives a valid token with the scopes a test needs, for five minutes.
  • token(scopes, audience, lifetime) builds the invalid tokens the negative tests need, such as another audience.
  • It uses only the JDK: a JSON header and claims, Base64URL-encoded, signed with SHA256withRSA.

Checkpoint: open TestTokens.java in your IDE. It compiles as it is.

A test signing key belongs in a repository only because it protects nothing. In a real set-up, only the authorization server holds the private key, and the service trusts its published public keys.

Set Up the Test Class

Goal: start the application on a free port, and point REST Assured at it.

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
package com.javanibble.module_11.section_03;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;

import com.javanibble.module_11.support.TestTokens;

import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;

import java.time.Duration;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RandomPortServerTest {

    @LocalServerPort
    private int port;

    private RequestSpecification accounts() {
        return given().baseUri("http://localhost").port(port).basePath("/api/v1/accounts");
    }
}

What’s happening:

  • @SpringBootTest(webEnvironment = RANDOM_PORT) starts the whole application, in about 0.6 seconds here, and Spring reuses it for every test in the class.
  • @LocalServerPort injects the port, such as 61201.
  • given is the plain RestAssured one: this is real HTTP, and RestAssuredMockMvc never opens a socket.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Test With Real Signed Tokens

List Accounts as a Reader

Goal: prove a real token with accounts:read gets through.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void aReaderCanListAccounts() {
    accounts()
        .auth().oauth2(TestTokens.withScopes("accounts:read"))
    .when()
        .get()
    .then()
        .statusCode(200)
        .body("id", hasItems("acc-1001", "acc-1002"));
}

What’s happening:

  • auth().oauth2(..) sends Authorization: Bearer <token>, and the service decodes, verifies and validates it.
  • The base path is the whole collection, so get() needs no path.
  • hasItems(..), not contains(..): the application is shared by every test in the class, and another test opens an account, so the list may have more than two. This is the fix for the shared-service problem from the web slice.

Checkpoint: run RandomPortServerTest from your IDE. One test runs and passes, after the application starts.

Open an Account and Read It Back

Goal: act as two clients: a writer opens an account, and a reader reads it.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
void aWriterCanOpenAnAccountAndAReaderCanReadIt() {
    String location = accounts()
        .auth().oauth2(TestTokens.withScopes("accounts:write"))
        .contentType(ContentType.JSON)
        .body("{\"iban\": \"NL20INGB0001234567\", \"owner\": \"Lotte Laan\", \"currency\": \"EUR\"}")
    .when()
        .post()
    .then()
        .statusCode(201)
        .extract().header("Location");

    given().baseUri("http://localhost").port(port)
        .auth().oauth2(TestTokens.withScopes("accounts:read"))
    .when()
        .get(location)
    .then()
        .statusCode(200)
        .body("owner", equalTo("Lotte Laan"));
}

What’s happening:

  • Two tokens with different scopes act as two clients.
  • The Location is an absolute path, /api/v1/accounts/acc-1003, so the second request is built without the base path.
  • The test checks data it created itself, so other tests can’t change the outcome.

Checkpoint: run the class again. Two tests pass.

Build a request for a Location without the base path. With it, the request went to /api/v1/accounts/api/v1/accounts/acc-1003, and got 404 with No static resource api/v1/accounts/api/v1/accounts/acc-1003.

Prove Each Token Check Is Wired In

Refuse an Expired Token

Goal: send a token whose lifetime is over.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void anExpiredToken() {
    accounts()
        .auth().oauth2(TestTokens.token(List.of("accounts:read"), TestTokens.AUDIENCE, Duration.ofMinutes(-5)))
    .when()
        .get()
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", containsString("invalid_token"));
}

What’s happening:

  • A negative lifetime gives a token whose exp is five minutes before now.
  • The service answers 401 with error="invalid_token".

Checkpoint: run the class again. Three tests pass.

This test doesn’t test expiry. TestTokens sets iat to now, so with a negative lifetime, exp comes before iat, and the token is refused with expiresAt must be after issuedAt, a malformed token, before expiry is checked. With the expiry validator removed from SecurityConfig, all six tests still passed. Exercise 1 builds a token that’s really expired, and that test failed with 200 when the validator was removed.

Refuse a Token for Another Audience

Goal: send a correctly signed, current token issued for another API.

Add this test to the class:

1
2
3
4
5
6
7
8
9
@Test
void aTokenForAnotherAudience() {
    accounts()
        .auth().oauth2(TestTokens.token(List.of("accounts:read"), "payments-api", Duration.ofMinutes(5)))
    .when()
        .get()
    .then()
        .statusCode(401);
}

What’s happening:

  • The token is valid in every way but one: it was issued for payments-api.
  • The audience check is a custom validator in SecurityConfig, and the reason is The aud claim is not valid.
  • This is the only test in the module that proves the validator is wired in, as Make a Test Fail shows.

Checkpoint: run the class again. Four tests pass.

Refuse the Wrong Scope

Goal: prove a valid token without the right scope gets 403, not 401.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void theWrongScope() {
    accounts()
        .auth().oauth2(TestTokens.withScopes("accounts:write"))
    .when()
        .get("/{id}", "acc-1001")
    .then()
        .statusCode(403)
        .header("WWW-Authenticate", containsString("insufficient_scope"));
}

What’s happening:

  • The token is valid, so the service knows who’s calling: the answer is 403, not 401.
  • The rule is the one the web slice tested, now with a real token.

Checkpoint: run the class again. Five tests pass.

Read an Unknown Account Over HTTP

Goal: check that errors arrive as problem details through the real servlet container.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void anUnknownAccountIsAProblem() {
    accounts()
        .auth().oauth2(TestTokens.withScopes("accounts:read"))
    .when()
        .get("/{id}", "acc-9999")
    .then()
        .statusCode(404)
        .contentType("application/problem+json")
        .body("status", equalTo(404))
        .body("detail", equalTo("Account acc-9999 does not exist"));
}

What’s happening:

  • The error travels through the servlet container’s error handling, as in production, and still arrives as an RFC 9457 problem detail.

Checkpoint: run the class again. All six tests pass.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-11 -Dtest=RandomPortServerTest

You should see a result similar to the following, after Spring Boot’s start-up log:

1
2
3
4
5
6
7
[INFO] Running com.javanibble.module_11.section_03.RandomPortServerTest
... Started RandomPortServerTest in 0.587 seconds (process running for 0.904)
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.353 s -- in com.javanibble.module_11.section_03.RandomPortServerTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In SecurityConfig.jwtDecoder(..), replace the setJwtValidator(..) call with decoder.setJwtValidator(JwtValidators.createDefault());, which drops the audience check, and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   RandomPortServerTest.aTokenForAnotherAudience:89 1 expectation failed.
Expected status code <401> but was <200>.

One test failed, and it’s the one about the audience: a token for payments-api now reads accounts. That’s how a negative test should behave. Do the same with the expiry validator, and nothing fails, which is why the danger callout above matters.

Restore SecurityConfig and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
ConnectException: Connection refusedThe request went to the default port 8080, not the random oneSet port(port) from @LocalServerPort
cannot find symbol: class LocalServerPortThe Spring Boot 3 packageImport org.springframework.boot.test.web.server.LocalServerPort
404 No static resource api/v1/accounts/api/v1/..A Location with the base path still setBuild that request without the base path
A list check fails with extra itemsAnother test changed the shared application’s dataUse hasItems(..), or check data the test created
expiresAt must be after issuedAtexp is earlier than iatSet iat before exp, as in Exercise 1

Try It Yourself

Exercise 1: Send a Really Expired Token

Add an overload token(List<String> scopes, String audience, Instant issuedAt, Instant expiresAt) to TestTokens, and make the existing token(..) call it. Then add a test called aReallyExpiredToken with a token issued ten minutes ago that expired five minutes ago, and check for 401 with Jwt expired at in WWW-Authenticate.

Hint

Move the body of token(scopes, audience, lifetime) into the new overload, with issuedAt and expiresAt in the claims. The old one then becomes token(scopes, audience, now, now.plus(lifetime)).

Solution

In TestTokens:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static String token(List<String> scopes, String audience, Duration lifetime) {
    Instant now = Instant.now();
    return token(scopes, audience, now, now.plus(lifetime));
}

public static String token(List<String> scopes, String audience, Instant issuedAt, Instant expiresAt) {
    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claims = """
        {"iss":"https://auth.example.com","sub":"tpp-client","aud":"%s","scope":"%s","iat":%d,"exp":%d}"""
        .formatted(audience, String.join(" ", scopes), issuedAt.getEpochSecond(), expiresAt.getEpochSecond());
    String signingInput = encode(header) + "." + encode(claims);
    try {
        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initSign(KEY);
        signer.update(signingInput.getBytes(StandardCharsets.US_ASCII));
        return signingInput + "." + BASE64URL.encodeToString(signer.sign());
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

In RandomPortServerTest:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aReallyExpiredToken() {
    Instant tenMinutesAgo = Instant.now().minus(Duration.ofMinutes(10));

    accounts()
        .auth().oauth2(TestTokens.token(List.of("accounts:read"), TestTokens.AUDIENCE, tenMinutesAgo, tenMinutesAgo.plus(Duration.ofMinutes(5))))
    .when()
        .get()
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", containsString("Jwt expired at"));
}

Add import java.time.Instant; to the test class. A token that expired only 30 seconds ago was still accepted, because of the 60-second clock skew, so keep the expiry well in the past.

Exercise 2: Refuse a Forged Signature

Add a test called aTamperedSignature. Take a valid reader token, change the last two characters of its signature, and check for 401 with Invalid signature in WWW-Authenticate.

Hint

The signature is the part after the last .. Replace the last two characters with AA, or with BB if they already are AA.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aTamperedSignature() {
    String token = TestTokens.withScopes("accounts:read");
    String tampered = token.substring(0, token.length() - 2) + (token.endsWith("AA") ? "BB" : "AA");

    accounts()
        .auth().oauth2(tampered)
    .when()
        .get()
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", containsString("Invalid signature"));
}

Summary

You built RandomPortServerTest, which starts the whole accounts service on a free port and tests it with real signed tokens: a reader and a writer get through, an expired-looking token, a token for another audience and the wrong scope are refused, and errors arrive as problem details over HTTP. You also found out which of those tests really prove their check.

  • @SpringBootTest(webEnvironment = RANDOM_PORT) starts the whole application; @LocalServerPort gives the port, and plain REST Assured tests it over HTTP.
  • Real tokens from a test key let the tests check signature, expiry and audience, which a stand-in token skips.
  • A negative token test must fail when its check is removed: the audience test does; the repository’s expiry test doesn’t, because its token is malformed.
  • Spring Security allows 60 seconds of clock skew, so an “expired” token must be well past its expiry.
  • The application is shared by every test in the class: check data a test created, or use hasItems(..).

Here are the commands you used in this guide:

1
mvn test -pl module-11 -Dtest=RandomPortServerTest

What’s Next

Next: continue with Keep Versions Aligned Under Spring Boot’s Dependency Management, which makes sure the module’s tests run on the JUnit, Jackson and REST Assured versions you chose.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.