Post

Write a Custom Authentication Scheme in REST Assured

Write an API key scheme with ContextAuthenticationScheme (REST Assured 6.3), use it in a specification, remove it with auth().none(), replace it with another scheme, and set it as the global default.

Write a Custom Authentication Scheme in REST Assured

The partner API doesn’t use Basic or OAuth 2.0: it wants an API key in an X-API-Key header. You add the header to the shared specification, and every test passes. Then you write the test that matters for security, a request without the key, and find you can’t take the header back out: auth().none() leaves it in place, and the request still gets 200. An authentication scheme behaves differently. In this guide, you’ll write the API key as a scheme, so a test can remove or replace it like any other.

Level: Advanced · Time: 20 minutes · Part of: Module 8: Filters and Extensibility, section 4

What You’ll Build

You’ll build a test class called CustomAuthenticationTest with four tests, around a one-line API key scheme. The tests use the scheme in a specification, remove it with auth().none(), replace it with Basic, and set it as the global default.

The negative test uses the same specification as the positive one, and removes only the key:

1
2
3
4
5
6
7
8
GET /api/v1/partner/accounts HTTP/1.1
Host: localhost:<port>
X-Correlation-Id: 34432cb9-4f5e-465e-a2d3-6e4657f0caee

HTTP/1.1 401 Unauthorized
Content-type: application/problem+json; charset=utf-8

{"type":"about:blank","title":"Unauthorized","status":401,"detail":"A valid X-API-Key is required","instance":"/api/v1/partner/accounts"}

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

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

In this guide, you will:

  • Write an API key scheme.
  • Remove and replace it per request.
  • Set it as the global default.

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 CustomAuthenticationTest in a new section_04 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (CustomAuthenticationTest.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 doesn’t cover answering authentication challenges, such as Digest or NTLM, from a custom scheme, though the context it uses can do both.

Understand Custom Authentication Schemes

The problem. Partner APIs often authenticate with a key in a custom header. As a plain header in a shared specification it works for every positive test, but a header is merged into every request: a test can add a second value, not take the first away. That leaves no clean way to test a missing or wrong key, which is the test that proves the API checks.

The concept. REST Assured treats authentication as one slot on a request. Whatever fills the slot, Basic, OAuth 2.0 or your own scheme, is replaced when a request sets another one, and emptied by auth().none(). ContextAuthenticationScheme, new in REST Assured 6.3, lets you fill the slot yourself. It’s a functional interface whose one method gets an AuthenticationContext, which can set headers, answer Basic challenges, sign with OAuth or use a client certificate, without any Apache HttpClient 4 types.

 A header in a specificationAn authentication scheme
A request sets another valueBoth values are sentThe request’s scheme replaces it
auth().none()The header is still sentRemoved

When to use each. Write a scheme for credentials in a custom header, such as an API key, or a token the tests shouldn’t know how to fetch. Use a plain header for values that aren’t credentials. Don’t use a scheme for request signing: as you’ll see, filters can’t see what a scheme adds, so a signer couldn’t cover it.

Put credentials in the authentication slot, so a test can take them away.

Meet the API Under Test

The tests use one endpoint of SignedPaymentsApi, the same one as in section 1:

RequestRules
GET /api/v1/partner/accountsNeeds X-API-Key: partner-key-123 and an X-Correlation-Id

With both, it answers 200 with one account, [{"id":"acc-1001","iban":"NL91ABNA0417164300"}]. Without a valid key, it answers 401 with the detail A valid X-API-Key is required. The CorrelationIdFilter from section 1 adds the correlation id.

Your tests check these values:

  • The status: 200 with the key, 401 without it.
  • The number of accounts, which proves the request got through.

Write an API Key Scheme

Set Up the Test Class

Goal: create the test class with the API, the scheme, and a specification that uses 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.javanibble.module_08.section_04;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasSize;

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

import io.restassured.RestAssured;
import io.restassured.authentication.ContextAuthenticationScheme;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;

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

class CustomAuthenticationTest {

    private static SignedPaymentsApi api;

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

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

    static ContextAuthenticationScheme apiKey(String key) {
        return context -> context.header("X-API-Key", key);
    }

    private static RequestSpecification partnerApi() {
        return new RequestSpecBuilder()
            .setBaseUri(api.baseUri()).setPort(api.port())
            .addFilter(new CorrelationIdFilter())
            .setAuth(apiKey(SignedPaymentsApi.PARTNER_API_KEY))
            .build();
    }
}

What’s happening:

  • apiKey(..) is the whole scheme: a lambda that gets the AuthenticationContext and sets the header.
  • setAuth(..) puts it in the specification’s authentication slot, next to the base URI and the CorrelationIdFilter.
  • Nothing in partnerApi() adds X-API-Key as a header, so nothing outside the slot needs removing later.

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

ContextAuthenticationScheme replaces implementing AuthenticationScheme.authenticate(HTTPBuilder), which is deprecated in 6.3 and removed in REST Assured 7, because HTTPBuilder exposes HttpClient 4. In REST Assured 7, AuthenticationScheme itself takes the same lambda, and ContextAuthenticationScheme is deprecated; the OpenRewrite recipe io.restassured.UpgradeToRestAssured7 makes the change for you. REST Assured 7 was at release candidate 1 when this guide was written.

Use the Scheme in a Specification

Goal: prove the scheme sends the key.

Add this test to the class:

1
2
3
4
@Test
void theSchemeInASpecification() {
    given(partnerApi()).when().get("/api/v1/partner/accounts").then().statusCode(200).body("$", hasSize(1));
}

What’s happening:

  • The specification’s scheme adds X-API-Key: partner-key-123, and the filter adds the correlation id.
  • The API answers 200 with one account. The test itself mentions no credentials.

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

Filters and log() don’t see what a scheme adds. A filter that read X-API-Key on this request found null, and log().headers() listed only Accept and X-Correlation-Id, though the server received the key. That keeps the key out of request logs, but it also means a signing filter can’t cover it.

Remove and Replace the Scheme

Remove It With auth().none()

Goal: send the same request without the key, and prove the API refuses it.

Add this test to the class:

1
2
3
4
@Test
void authNoneRemovesIt() {
    given(partnerApi()).auth().none().when().get("/api/v1/partner/accounts").then().statusCode(401);
}

What’s happening:

  • auth().none() empties the authentication slot, so the scheme from the specification isn’t applied.
  • Everything else in the specification stays: the base URI, the port and the correlation id filter. The key is the only difference.
  • The API answers 401 with A valid X-API-Key is required.

Checkpoint: run the class again. Two tests pass.

Replace It With Another Scheme

Goal: show that a request has one scheme, and setting another drops the key.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void aWrongKey() {
    given().baseUri(api.baseUri()).port(api.port())
        .filter(new CorrelationIdFilter())
        .auth().preemptive().basic("not", "an-api-key")          // another scheme, so no X-API-Key at all
    .when()
        .get("/api/v1/partner/accounts")
    .then()
        .statusCode(401);
}

What’s happening:

  • The request uses preemptive Basic, which sends Authorization: Basic .. and no API key, so the API answers 401.
  • The same holds on top of the specification: against a server that echoes what it received, given(partnerApi()).auth().preemptive().basic(..) sent Authorization: Basic bm90OmFuLWFwaS1rZXk= and no X-API-Key.
  • Two schemes never combine: the last one set fills the slot.

Checkpoint: run the class again. Three tests pass.

Don’t try to override a scheme’s header with header(..). With the scheme in place, a request header X-API-Key: wrong didn’t reach the server; it received only the scheme’s key. To send a different key, replace the scheme, as Exercise 1 shows.

Set the Scheme as the Global Default

Set RestAssured.authentication

Goal: give every request the scheme, and undo it afterwards.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void asTheDefaultForEveryRequest() {
    RestAssured.authentication = apiKey(SignedPaymentsApi.PARTNER_API_KEY);
    try {
        given().baseUri(api.baseUri()).port(api.port())
            .filter(new CorrelationIdFilter())
        .when()
            .get("/api/v1/partner/accounts")
        .then()
            .statusCode(200);
    } finally {
        RestAssured.reset();
    }
}

What’s happening:

  • RestAssured.authentication sets the scheme every request starts with, so a request with no auth() gets the key.
  • It’s global state, like the global filters in section 1: RestAssured.reset() in finally undoes it, even when the test fails.
  • A specification is usually the better place, because only the tests that use it send the key.

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

A global scheme without reset() sends the key with every later request, in every test class that runs in the same JVM, including requests to other servers. Reset in finally, or keep the scheme in a specification.

Run the Tests

Run the following command from the repository root:

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

You should see a result similar to the following:

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

Make a Test Fail

In partnerApi(), replace .setAuth(apiKey(SignedPaymentsApi.PARTNER_API_KEY)) with .addHeader("X-API-Key", SignedPaymentsApi.PARTNER_API_KEY), and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   CustomAuthenticationTest.authNoneRemovesIt:62 1 expectation failed.
Expected status code <401> but was <200>.

With the key as a plain header, auth().none() has nothing to remove: the header is still sent, and the API accepts the request. The positive test still passes, so only the negative test notices. That’s the whole case for a scheme.

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

Troubleshooting

SymptomLikely causeFix
auth().none() still sends the keyThe key is a header in the specification, not a schemeMove it into setAuth(..)
A test sends a second key value, and the API ignores itHeaders are merged, so both values are sentReplace the scheme instead of adding a header
A filter or log() doesn’t show X-API-KeyScheme headers are added after filters and logging runCheck what the server received, not the request log
Later tests send the key unexpectedlyRestAssured.authentication was set without reset()Call RestAssured.reset() in finally

Try It Yourself

Exercise 1: Replace the Key With a Wrong One

Add a test called aWrongKeyFromAnotherSpecification. Start from partnerApi(), and merge in a second specification whose only setting is setAuth(apiKey("wrong-key")). Check that the API answers 401.

Hint

given(partnerApi()).spec(..) merges a second specification into the request. Its scheme replaces the first one, the way a request’s scheme does.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void aWrongKeyFromAnotherSpecification() {
    RequestSpecification wrongKey = new RequestSpecBuilder().setAuth(apiKey("wrong-key")).build();

    given(partnerApi())
        .spec(wrongKey)
    .when()
        .get("/api/v1/partner/accounts")
    .then()
        .statusCode(401);
}

Exercise 2: Prove a Header Can’t Be Removed

Add a test called aHeaderSurvivesAuthNone. Build a specification like partnerApi(), but with the key added with addHeader(..) instead of setAuth(..). Check that a request with auth().none() still gets 200, and that a request that adds header("X-API-Key", "wrong") still gets 200 too.

Hint

The header from the specification is sent in both cases. In the second, both values are sent, and the API reads the first one.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void aHeaderSurvivesAuthNone() {
    RequestSpecification withHeader = new RequestSpecBuilder()
        .setBaseUri(api.baseUri()).setPort(api.port())
        .addFilter(new CorrelationIdFilter())
        .addHeader("X-API-Key", SignedPaymentsApi.PARTNER_API_KEY)
        .build();

    given(withHeader).auth().none().when().get("/api/v1/partner/accounts").then().statusCode(200);
    given(withHeader).header("X-API-Key", "wrong").when().get("/api/v1/partner/accounts").then().statusCode(200);
}

Against a server that echoes what it received, the second request arrived with X-API-Key: partner-key-123 and X-API-Key: wrong.

Summary

You built CustomAuthenticationTest, which uses a one-line API key scheme in a specification, removes it with auth().none(), replaces it with Basic, and sets it as the global default. The negative test now uses the same specification as every other test, and removes only the key.

  • ContextAuthenticationScheme, new in REST Assured 6.3, is a functional interface: a lambda that sets headers through an AuthenticationContext, with no HttpClient 4 types.
  • Use it with setAuth(..) in a specification, or RestAssured.authentication globally, with a reset().
  • A request has one scheme: setting another replaces it, and auth().none() removes it. A header in a specification can only be added to.
  • Filters and log() don’t see a scheme’s headers, so a scheme isn’t the place for anything a signer must cover.
  • In REST Assured 7, AuthenticationScheme takes the same lambda, and ContextAuthenticationScheme is deprecated.

Here are the commands you used in this guide:

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

What’s Next

Next: continue with Use Parsers and Failure Listeners in REST Assured, which reads the legacy endpoint’s mislabelled JSON with a parser, and reacts to failing tests with a listener.

The code:

Go deeper:

Related guides:

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