Post

Sign Requests With HTTP Message Signatures in REST Assured

Sign every request with HTTP Message Signatures (RFC 9421) and Content-Digest (RFC 9530) in an OrderedFilter that runs last, and prove the server checks the signature with unsigned, tampered, wrongly signed and stale requests.

Sign Requests With HTTP Message Signatures in REST Assured

A bearer token says who sent a request. It doesn’t say that the request arrived as it was sent. For payments that matters: an attacker who can change 100.00 into 100000.00 on the way doesn’t need to steal anything else. That’s why FAPI and several open banking standards require signed requests, where a signature covers the method, the path, a digest of the body and chosen headers, so any change breaks it. In this guide, you’ll sign every request in one filter, and prove that the server rejects every request it should.

Level: Advanced · Time: 30 minutes · Part of: Module 8: Filters and Extensibility, section 3

What You’ll Build

You’ll build a filter called HttpMessageSignatureFilter, and a test class called RequestSigningTest with six tests. Two send signed requests that the server accepts. Four prove the server checks: an unsigned request, a body changed after signing, the wrong secret and a stale signature are all rejected.

The filter adds three headers to a payment:

1
2
3
4
5
6
7
8
9
10
11
POST /api/v1/payments HTTP/1.1
Host: localhost:<port>
Content-Type: application/json
X-Correlation-Id: 540e5a94-0b6c-478f-807a-b9adf18c1672
Content-Digest: sha-256=:3m3Qtp6ZlPENuO2bxBxlMB8N/XFel/8o9FygCA36zXE=:
Signature-Input: sig1=("@method" "@path" "content-digest" "x-correlation-id");created=1795331777;keyid="tpp-key-1"
Signature: sig1=:gMj7AdR31z9AX7n9GoOpVLdts0EgkGDzcNYqcWJ1Fpg=:

{"creditorIban": "NL69INGB0123456789", "amount": "100.00"}

HTTP/1.1 201 Created

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:

  • Write a signing filter.
  • Send signed requests.
  • Prove the server checks the signature.

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 RequestSigningTest in a new section_03 package next to the classes from the previous sections, and follow every heading below. If you copied HttpMessageSignatureFilter in the previous section, read its step and compare.
  • Skip ahead: open the finished class (RequestSigningTest.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 Write Request and Response Filters in REST Assured.

Out of scope: this guide signs with a shared secret (hmac-sha256). It doesn’t cover signing with private keys, such as RSA or ECDSA, or JWS-signed bodies, though the filter’s shape stays the same.

Understand HTTP Message Signatures

The problem. TLS protects a request between two hops, but a payment can pass through proxies and gateways, and a token proves only who sent it. Without a signature, nothing proves the amount or the creditor is what the client sent. And a server that accepts any signature looks exactly like one that checks, until someone tests what it rejects.

The concept. The signed payments API uses two standards. Content-Digest (RFC 9530) is a hash of the body. HTTP Message Signatures (RFC 9421) is a signature over chosen parts of the request. A signed request carries three headers:

HeaderHolds
Content-Digestsha-256=:<base64>:, the SHA-256 of the body
Signature-InputThe covered components, when the signature was created, and the key id
Signaturesig1=:<base64>:, the HMAC-SHA256 of the signature base with a shared secret

The signature base has one line per covered component, such as "@method": POST, and ends with a "@signature-params" line. Client and server build it the same way. The body is covered through its digest: change the body and the digest no longer matches, change the digest and the signature no longer matches.

When to use each. Sign in a filter, so no test can forget, and make it an OrderedFilter that runs last, after every filter that changes the request. Then write as many negative tests as positive ones: the positive tests prove the client signs; only the negative tests prove the server checks.

A signature is only as good as the server’s check, so test what it rejects.

Meet the API Under Test

SignedPaymentsApi requires a signature on its payment endpoints:

RequestRules
POST /api/v1/paymentsX-Correlation-Id; signed, covering @method @path content-digest x-correlation-id; a correct Content-Digest
GET /api/v1/payments/{id}X-Correlation-Id; signed, covering @method @path x-correlation-id

The shared secret for key id tpp-key-1 is SignedPaymentsApi.TPP_SECRET. A signature whose created time is more than five minutes from the server’s clock is rejected. Every signature problem gets 401, with a WWW-Authenticate: Signature error=".." header and a problem detail that names the problem:

Problemdetail
No Signature-Input or SignatureThe request is not signed
The body doesn’t match the digestContent-Digest doesn't match the body
The HMAC doesn’t matchThe signature is invalid
created is too far offThe signature is too old
An unknown key idUnknown keyid <id>

Your tests check these values:

  • The status: 201 or 200 for a signed request, 401 for every problem.
  • The detail, which proves the server refused for the reason the test meant.

Write the Signing Filter

Set Up the Test Class

Goal: create the test class with a payment, the API, and helpers for the base request and the signer.

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
42
43
44
45
46
47
48
49
50
package com.javanibble.module_08.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.startsWith;

import com.javanibble.module_08.support.CorrelationIdFilter;
import com.javanibble.module_08.support.HttpMessageSignatureFilter;
import com.javanibble.signing.SignedPaymentsApi;

import io.restassured.filter.FilterContext;
import io.restassured.filter.OrderedFilter;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import io.restassured.specification.RequestSpecification;

import java.time.Clock;
import java.time.Duration;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class RequestSigningTest {

    private static final String PAYMENT = "{\"creditorIban\": \"NL69INGB0123456789\", \"amount\": \"100.00\"}";

    private static SignedPaymentsApi api;

    @BeforeAll
    static void startApi() {
        api = SignedPaymentsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification api() {
        return given().baseUri(api.baseUri()).port(api.port()).filter(new CorrelationIdFilter());
    }

    private static HttpMessageSignatureFilter signer() {
        return new HttpMessageSignatureFilter(SignedPaymentsApi.TPP_KEY_ID, SignedPaymentsApi.TPP_SECRET);
    }
}

What’s happening:

  • api() sets the base URI and port, and adds the CorrelationIdFilter from section 1, but no signer, so each test decides how to sign.
  • signer() builds a signing filter with the right key id and secret.

Checkpoint: the class compiles once HttpMessageSignatureFilter exists. If you haven’t got it yet, write it in the next step.

Write the Signing Filter

Goal: write a filter that adds Content-Digest, Signature-Input and Signature, and runs after every other filter.

Create this class in the support package:

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.javanibble.module_08.support;

import io.restassured.filter.FilterContext;
import io.restassured.filter.OrderedFilter;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class HttpMessageSignatureFilter implements OrderedFilter {

    private final String keyId;
    private final String secret;
    private final Clock clock;

    public HttpMessageSignatureFilter(String keyId, String secret) {
        this(keyId, secret, Clock.systemUTC());
    }

    public HttpMessageSignatureFilter(String keyId, String secret, Clock clock) {
        this.keyId = keyId;
        this.secret = secret;
        this.clock = clock;
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE - 1;                                // leave room for a "tamper in transit" demo
    }

    @Override
    public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
                           FilterContext context) {
        List<String> components = new ArrayList<>(List.of("@method", "@path"));
        Object body = request.getBody();
        String digest = null;
        if (body != null) {
            if (!(body instanceof String text)) {
                throw new IllegalStateException("This filter signs String bodies only, not " + body.getClass());
            }
            digest = "sha-256=:" + Base64.getEncoder().encodeToString(sha256(text.getBytes(StandardCharsets.UTF_8))) + ":";
            request.header("Content-Digest", digest);
            components.add("content-digest");
        }
        components.add("x-correlation-id");

        String params = components.stream().map(c -> "\"" + c + "\"").collect(Collectors.joining(" ", "(", ")"))
                + ";created=" + clock.instant().getEpochSecond() + ";keyid=\"" + keyId + "\"";

        StringBuilder base = new StringBuilder();
        for (String component : components) {
            String value = switch (component) {
                case "@method" -> request.getMethod().toUpperCase(Locale.ROOT);
                case "@path" -> URI.create(request.getURI()).getRawPath();
                case "content-digest" -> digest;
                default -> request.getHeaders().getValue(component);
            };
            base.append('"').append(component).append("\": ").append(value).append('\n');
        }
        base.append("\"@signature-params\": ").append(params);

        request.header("Signature-Input", "sig1=" + params);
        request.header("Signature", "sig1=:" + hmac(base.toString()) + ":");
        return context.next(request, responseSpec);
    }

    private String hmac(String data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return Base64.getEncoder().encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }

    private static byte[] sha256(byte[] data) {
        try {
            return MessageDigest.getInstance("SHA-256").digest(data);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
}

What’s happening:

  • With a body, the filter hashes it, adds Content-Digest, and covers content-digest. Without one, the digest is left out.
  • It builds the signature base, one line per component, ending with "@signature-params", and adds Signature-Input and the HMAC as Signature.
  • getOrder() returns LOWEST_PRECEDENCE - 1, so the signer runs after every ordinary filter, including the CorrelationIdFilter whose header it signs. It leaves one place after it for the tampering demo.
  • The Clock defaults to the system clock; a test can pass one set in the past.

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

The filter is written from the RFCs, independently of the server’s code. If the test reused the server’s signing code, a bug in it would be on both sides, and every test would still pass.

Send Signed Requests

Sign a POST

Goal: post a signed payment, and see the server accept it.

Add this test to RequestSigningTest:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aSignedPostIsAccepted() {
    api()
        .filter(signer())
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(201)
        .body("amount", equalTo("100.00"));
}

What’s happening:

  • The test contains no signing code: the filter adds the three headers shown in What You’ll Build.
  • The server recomputes the digest and the HMAC, finds both match, and creates the payment.

Checkpoint: run RequestSigningTest from your IDE. One test runs and passes.

By the time filters run, REST Assured has already serialized an object body, so a Map arrives in the filter as a String and is signed like any other; a signed Map payment got 201. A byte[] or a File body fails in the filter with IllegalStateException: This filter signs String bodies only, not class [B.

Sign a GET

Goal: fetch a payment with a signed request that has no body.

Add this test to the class:

1
2
3
4
5
6
7
8
@Test
void aSignedGetIsAccepted() {
    String id = api().filter(signer()).contentType(ContentType.JSON).body(PAYMENT)
        .when().post("/api/v1/payments")
        .then().statusCode(201).extract().path("paymentId");

    api().filter(signer()).when().get("/api/v1/payments/{id}", id).then().statusCode(200);
}

What’s happening:

  • The test creates a payment, then fetches it by its id.
  • The GET has no body, so it gets no Content-Digest, and its Signature-Input covers ("@method" "@path" "x-correlation-id").

Checkpoint: run the class again. Two tests pass.

Prove the Server Checks

Reject an Unsigned Request

Goal: prove the server refuses a payment with no signature at all.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
@Test
void anUnsignedRequestIsRejected() {
    api()
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", startsWith("Signature"));
}

What’s happening:

  • Without the signer, the request has no Signature-Input or Signature.
  • The server answers 401 with WWW-Authenticate: Signature error="The request is not signed", naming the scheme it expects.

Checkpoint: run the class again. Three tests pass.

Reject a Body Changed After Signing

Goal: play an attacker who changes the amount after the request was signed.

Add this test and this filter 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
@Test
void aBodyChangedAfterSigningIsRejected() {
    api()
        .filter(signer())
        .filter(new TamperInTransit())                           // runs after the signer
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(401)
        .body("detail", equalTo("Content-Digest doesn't match the body"));
}

/** Changes the amount after the request was signed, as an attacker in the middle would. */
private static final class TamperInTransit implements OrderedFilter {
    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
                           FilterContext context) {
        request.body(request.<String>getBody().replace("100.00", "100000.00"));
        return context.next(request, responseSpec);
    }
}

What’s happening:

  • TamperInTransit has the order LOWEST_PRECEDENCE, one after the signer, so it changes the body after the signature was made.
  • The server hashes the body it received, finds it doesn’t match Content-Digest, and refuses.
  • This is why the signer’s order is LOWEST_PRECEDENCE - 1: it leaves exactly one place after it.

Checkpoint: run the class again. Four tests pass.

A header changed after signing breaks the signature too. A filter that replaced X-Correlation-Id after the signer got 401 with The signature is invalid, because the header is a covered component.

Reject the Wrong Secret

Goal: prove the server refuses a signature made with a secret it doesn’t share.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aSignatureWithTheWrongSecretIsRejected() {
    api()
        .filter(new HttpMessageSignatureFilter(SignedPaymentsApi.TPP_KEY_ID, "not-the-secret"))
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(401)
        .body("detail", equalTo("The signature is invalid"));
}

What’s happening:

  • The digest is correct, so the server gets past that check.
  • The HMAC wasn’t made with the client’s secret, so it doesn’t match the one the server computes.

Checkpoint: run the class again. Five tests pass.

Reject a Stale Signature

Goal: prove the server refuses a valid signature that’s ten minutes old.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void anOldSignatureIsRejected() {
    Clock tenMinutesAgo = Clock.offset(Clock.systemUTC(), Duration.ofMinutes(-10));

    api()
        .filter(new HttpMessageSignatureFilter(SignedPaymentsApi.TPP_KEY_ID, SignedPaymentsApi.TPP_SECRET, tenMinutesAgo))
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(401)
        .body("detail", containsString("too old"));
}

What’s happening:

  • A valid signature that’s ten minutes old could be a recorded request being replayed.
  • Clock.offset(..) moves the filter’s clock back, so created is ten minutes in the past, without waiting or changing the system time.

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

Don’t test a time-based rule with Thread.sleep(..): a five-minute rule would need a five-minute test. Inject a Clock into the code that reads the time, as the signer does.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-08 -Dtest=RequestSigningTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_08.section_03.RequestSigningTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.493 s -- in com.javanibble.module_08.section_03.RequestSigningTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In aBodyChangedAfterSigningIsRejected, delete the .filter(new TamperInTransit()) line and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   RequestSigningTest.aBodyChangedAfterSigningIsRejected:101 1 expectation failed.
Expected status code <401> but was <201>.

Without the attacker, the request arrives as it was signed, and the server accepts it. The failure shows that the test’s 401 came from the tampering, and nothing else. A negative test should fail like this when you remove the one thing it’s about.

Put the .filter(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
401 with The signature is invalid on a request that should passA filter changed a covered header after the signer, or the secret is wrongMake the signer run last, and check the key id and secret
401 with Content-Digest doesn't match the bodyThe body changed after signingMake sure no filter after the signer changes the body
401 with The signature is too old on a normal runAgainst a remote server, the two clocks are more than five minutes apart; locally, the Clock passed to the signer is offSynchronise the clocks, or check the Clock passed to the signer
IllegalStateException: This filter signs String bodies onlyThe body is a byte[] or a FileSend the body as a String or an object REST Assured serializes
log() shows no signature headersLogging runs before the signerLog in a filter ordered after the signer, or log the server’s view

Try It Yourself

Exercise 1: See a Tamperer Before the Signer Go Unnoticed

Add a test called aChangeBeforeSigningIsSigned. Add the signer, then an ordinary lambda filter that changes 100.00 into 100000.00, and post the payment. Check that the server answers 201 with the amount 100000.00, which shows why the signer must run last.

Hint

An ordinary filter has the order 1000, so it runs before the signer, however late it’s added. The signer then signs the changed body. Import io.restassured.filter.Filter.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void aChangeBeforeSigningIsSigned() {
    Filter changeTheAmount = (request, responseSpec, context) -> {
        request.body(request.<String>getBody().replace("100.00", "100000.00"));
        return context.next(request, responseSpec);
    };

    api()
        .filter(signer())
        .filter(changeTheAmount)                                 // added last, but runs before the signer
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(201)
        .body("amount", equalTo("100000.00"));
}

Add import io.restassured.filter.Filter; to the class.

Exercise 2: Reject an Unknown Key

Add a test called anUnknownKeyIdIsRejected. Sign the payment with the right secret, but the key id tpp-key-9, and check that the server answers 401 with the detail Unknown keyid tpp-key-9 and a WWW-Authenticate header that contains the same text.

Hint

Pass "tpp-key-9" as the first argument of new HttpMessageSignatureFilter(..). Use containsString(..) for the header.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void anUnknownKeyIdIsRejected() {
    api()
        .filter(new HttpMessageSignatureFilter("tpp-key-9", SignedPaymentsApi.TPP_SECRET))
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", containsString("Unknown keyid tpp-key-9"))
        .body("detail", equalTo("Unknown keyid tpp-key-9"));
}

Summary

You built HttpMessageSignatureFilter, which adds Content-Digest, Signature-Input and Signature to every request, and RequestSigningTest, which proves the server accepts signed requests and rejects unsigned, tampered, wrongly signed and stale ones. A payment’s amount can no longer change on its way without the server noticing, and the tests prove it.

  • HTTP Message Signatures (RFC 9421) sign chosen parts of a request; Content-Digest (RFC 9530) brings the body in through its hash.
  • Sign in an OrderedFilter with an order near LOWEST_PRECEDENCE, so it runs after every filter that changes the request.
  • Write the signer from the RFCs, not from the server’s code, and inject a Clock for time-based rules.
  • Prove the server checks with negative tests, and check the detail so each refuses for the reason you meant.
  • log() runs before the signer, so it never shows the signature headers.

Here are the commands you used in this guide:

1
mvn test -pl module-08 -Dtest=RequestSigningTest

What’s Next

Next: continue with Write a Custom Authentication Scheme in REST Assured, which writes an API key scheme with ContextAuthenticationScheme and uses it like the built-in ones.

The code:

Go deeper:

Related guides:

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