Post

Test HTTP Basic Authentication in REST Assured

Test HTTP Basic authentication, covering the 401 challenge, challenged Basic with auth().basic(..), preemptive Basic with auth().preemptive().basic(..), a server that never challenges, and wrong credentials.

Test HTTP Basic Authentication in REST Assured

Your test for the bank’s daily admin report sends the right user name and password with auth().basic(..), and gets a 404. The report exists, the password is right, and nothing in the test says why it failed. In this guide, you’ll learn the two ways REST Assured sends Basic credentials, see why the one that looks natural never sends them to a server that hides itself, and test the challenge, the right credentials and the wrong ones.

Level: Intermediate · Time: 20 minutes · Part of: Module 7: Authentication and Transport Security, section 1

What You’ll Build

You’ll build a test class called BasicAuthenticationTest with six tests. They trigger the server’s challenge, answer it with challenged and preemptive Basic, show challenged Basic failing against an endpoint that never challenges, and check that a wrong password is refused.

The first test sends a request without credentials, and checks the challenge:

1
2
3
4
5
6
7
8
GET /admin/health HTTP/1.1
Host: localhost:<port>

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="admin"
Content-type: application/problem+json; charset=utf-8

{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Admin credentials are required", ...}

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:

  • Check the server’s challenge.
  • Answer the challenge, or send credentials straight away.
  • Authenticate against a server that never challenges.
  • Test wrong credentials.

What You Need

  • About 20 minutes
  • JDK 26 or later
  • Maven 3.9 or later
  • An IDE (IntelliJ IDEA, VS Code or Eclipse)
  • Knowledge: you can check status codes and headers, as taught in Check Every Part of an HTTP Response. No earlier authentication knowledge is needed.

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 7, so you start from scratch. Create BasicAuthenticationTest in the module-07 test sources and follow every heading below.
  • Skip ahead: open the finished class (BasicAuthenticationTest.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.

Out of scope: this guide doesn’t cover bearer tokens, systematic negative security tests, or HTTPS; they’re taught in section 2, section 3 and section 5.

Understand HTTP Basic Authentication

The problem. REST Assured supports Basic authentication in one line, but there are two ways to send the credentials, and the one that looks natural doesn’t send them with the first request. Against most APIs that’s fine. Against an endpoint that hides itself from strangers, the credentials are never sent at all, and the test fails with a status that seems to make no sense.

The concept. A client sends Authorization: Basic <base64 of user:password>. The server can ask for it with a challenge: a 401 Unauthorized response with a WWW-Authenticate: Basic realm=".." header. REST Assured sends the credentials in one of two ways:

MethodRequestsWhen credentials are sent
auth().basic(user, password)Two, when the server challengesOnly after a 401 with a Basic challenge
auth().preemptive().basic(user, password)OneWith the first request

The first form is challenged: REST Assured sends the request without credentials, and only sends it again, with them, when the server answers with a challenge. The second is preemptive.

When to use each. Use preemptive Basic for APIs: it saves a round trip and works whether or not the server challenges. Use challenged Basic only when the challenge-and-answer exchange is itself what you test. Always test the wrong credentials too, and send Basic only over HTTPS outside your machine.

Send Basic credentials preemptively, and test the locked door as well as the key.

Meet the API Under Test

Module 7 tests a protected bank: an OAuth 2.0 authorization server and the resource server it protects, in one process. It runs on the JDK’s built-in HTTP server, like the APIs of the earlier modules, and starts on a free port. This section uses its two admin endpoints, both protected with the user admin and the password changeit:

EndpointWithout credentialsWith them
GET /admin/health401 with WWW-Authenticate: Basic realm="admin", a challenge{"status":"UP"}
GET /admin/report404 with No resource at /admin/report, to hide that the endpoint exists{"payments":42,"report":"daily"}

Hiding a protected endpoint behind a 404 is a common practice: a stranger can’t tell an admin page from a page that doesn’t exist. It also means the endpoint never challenges.

The credentials travel as Authorization: Basic YWRtaW46Y2hhbmdlaXQ=, the base64 of admin:changeit.

Your tests check these values:

  • The status and WWW-Authenticate header of the challenge.
  • The status of each request with credentials, and the report field of the admin report.

Check the Server’s Challenge

Set Up the Test Class

Goal: create the test class, start the bank’s API and add a request helper.

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
package com.javanibble.module_07.section_01;

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

import com.javanibble.auth.BankAuthApi;

import io.restassured.specification.RequestSpecification;

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

class BasicAuthenticationTest {

    private static BankAuthApi api;

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

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

    private static RequestSpecification bank() {
        return given().baseUri(api.baseUri()).port(api.port());
    }
}

What’s happening:

  • BankAuthApi is Module 7’s test server. It starts and stops like the APIs of the earlier modules.
  • bank() points requests at it. The admin endpoints have no base path.

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

Send a Request Without Credentials

Goal: check that the server answers with a Basic challenge.

1
2
3
4
5
6
7
8
9
@Test
void withoutCredentialsTheServerChallenges() {
    bank()
    .when()
        .get("/admin/health")
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", "Basic realm=\"admin\"");
}

What’s happening:

  • The body is an RFC 9457 problem, with the detail Admin credentials are required.
  • The WWW-Authenticate header is what makes it a challenge: it tells the client which scheme to use, and for which realm.

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

Answer the Challenge, or Send Credentials Straight Away

Answer With Challenged Basic

Goal: let REST Assured answer the challenge with credentials.

1
2
3
4
@Test
void challengedBasicAnswersTheChallenge() {
    bank().auth().basic("admin", "changeit").when().get("/admin/health").then().statusCode(200);
}

What’s happening:

  • Two requests go over the wire: one without credentials, which gets the challenge, and one with them, which gets 200.
  • The test sees only the second response.

Checkpoint: run the class again. Two tests pass.

auth().basic(..) sends two requests whenever the server challenges. Counted on a test server, it sent one request without an Authorization header and then one with it. That matters for logs, rate limits and endpoints with side effects.

Send Preemptive Basic

Goal: send the credentials with the first request.

1
2
3
4
@Test
void preemptiveBasicSendsCredentialsStraightAway() {
    bank().auth().preemptive().basic("admin", "changeit").when().get("/admin/health").then().statusCode(200);
}

What’s happening:

  • preemptive() adds the Authorization header to the first request, so one request is enough.
  • The server never has to challenge.

Checkpoint: run the class again. Three tests pass.

Authenticate Against a Server That Never Challenges

See Challenged Basic Fail

Goal: show that challenged Basic never sends the credentials to an endpoint that hides itself.

1
2
3
4
5
6
7
8
9
@Test
void challengedBasicFailsWhenTheServerNeverChallenges() {
    bank()
        .auth().basic("admin", "changeit")
    .when()
        .get("/admin/report")
    .then()
        .statusCode(404);
}

What’s happening:

  • REST Assured sends the first request without credentials and waits for a challenge.
  • The server answers 404, which isn’t a challenge, so REST Assured stops there.
  • The credentials were correct, but they never left the client. This is the 404 from the opening.

Checkpoint: run the class again. Four tests pass.

Use Preemptive Basic There

Goal: open the hidden endpoint with preemptive Basic.

1
2
3
4
5
6
7
8
9
10
@Test
void preemptiveBasicWorksThere() {
    bank()
        .auth().preemptive().basic("admin", "changeit")
    .when()
        .get("/admin/report")
    .then()
        .statusCode(200)
        .body("report", equalTo("daily"));
}

What’s happening:

  • The credentials are in the first request, so the server never has to ask.
  • The report body proves the request reached the protected endpoint.

Checkpoint: run the class again. Five tests pass.

Use preemptive Basic against an endpoint that hides itself. With challenged Basic, the credentials are never sent, and the test gets a 404 or a 403 that says nothing about authentication.

Test Wrong Credentials

Send the Wrong Password

Goal: prove that the endpoint is locked, not only that it can be opened.

1
2
3
4
@Test
void wrongCredentials() {
    bank().auth().preemptive().basic("admin", "guess").when().get("/admin/health").then().statusCode(401);
}

What’s happening:

  • A wrong password gets the same 401 and challenge as no credentials at all.
  • A test with the right credentials proves that the endpoint can be opened. Only a test with wrong ones proves that it’s locked: an endpoint that accepts every password passes the first kind of test.

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

Base64 is an encoding, not encryption: YWRtaW46Y2hhbmdlaXQ= decodes straight back to admin:changeit. Send Basic credentials only over HTTPS outside your machine, and keep the Authorization header out of logs, as Keep Secrets Out of REST Assured Logs shows.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-07 -Dtest=BasicAuthenticationTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_07.section_01.BasicAuthenticationTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.517 s -- in com.javanibble.module_07.section_01.BasicAuthenticationTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In preemptiveBasicWorksThere, change .auth().preemptive().basic(..) to .auth().basic(..) and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   BasicAuthenticationTest.preemptiveBasicWorksThere:81 1 expectation failed.
Expected status code <200> but was <404>.

The password is still right, but without preemptive() it waits for a challenge the endpoint never sends, so the only response is the hiding 404. When a test with correct credentials gets a 404 or 403 from a protected endpoint, check whether the credentials were sent at all. log().headers() shows the Authorization header when they were.

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

Troubleshooting

SymptomLikely causeFix
404 or 403 with the right credentialsChallenged Basic against an endpoint that never challengesUse auth().preemptive().basic(..)
401 with WWW-Authenticate: Basic realm="admin"The credentials are missing or wrongCheck the user name and password
The server sees two requests for one test requestauth().basic(..) answers a challenge with a second requestUse preemptive Basic
An Authorization: Basic .. header appears in a logThe header isn’t blacklistedAdd blacklistHeader("Authorization") to the log config

Try It Yourself

Exercise 1: Use the Wrong User Name

Add a test called aWrongUserNameIsRefusedEverywhere that sends preemptive Basic with the user name "root" and the right password. Check that /admin/health answers 401 with the challenge, and that /admin/report still hides itself with 404.

Hint

Start from wrongCredentials. The two endpoints refuse wrong credentials in their own way: one challenges, one hides.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aWrongUserNameIsRefusedEverywhere() {
    bank()
        .auth().preemptive().basic("root", "changeit")
    .when()
        .get("/admin/health")
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", "Basic realm=\"admin\"");

    bank()
        .auth().preemptive().basic("root", "changeit")
    .when()
        .get("/admin/report")
    .then()
        .statusCode(404);
}

Exercise 2: Keep the Password Out of the Log

Add a test called theBasicCredentialsAreNotLogged. Send preemptive Basic to /admin/report with log().headers(), through a log config that writes to an in-memory stream and blacklists Authorization. Check that the report is "daily", that the log shows Authorization=[ BLACKLISTED ], and that the base64 value YWRtaW46Y2hhbmdlaXQ= isn’t in it.

Hint

Build the config as in Keep Secrets Out of REST Assured Logs, with defaultStream(..) and blacklistHeader(..), and pass it with config(..). The header REST Assured adds for preemptive Basic is masked like any other.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
void theBasicCredentialsAreNotLogged() {
    ByteArrayOutputStream log = new ByteArrayOutputStream();

    bank()
        .config(config().logConfig(logConfig()
                .defaultStream(new PrintStream(log, true, StandardCharsets.UTF_8))
                .blacklistHeader("Authorization")))
        .auth().preemptive().basic("admin", "changeit")
        .log().headers()
    .when()
        .get("/admin/report")
    .then()
        .statusCode(200)
        .body("report", equalTo("daily"));

    String logged = log.toString(StandardCharsets.UTF_8);
    assertTrue(logged.contains("Authorization=[ BLACKLISTED ]"), logged);
    assertFalse(logged.contains("YWRtaW46Y2hhbmdlaXQ="), logged);
}

Add imports for ByteArrayOutputStream, PrintStream, StandardCharsets, logConfig, config, assertTrue and assertFalse to the class.

Summary

You built BasicAuthenticationTest, which checks the server’s challenge, answers it with challenged and preemptive Basic, shows challenged Basic failing against an endpoint that hides itself, and checks that a wrong password is refused. A correct password that gets a 404 is no longer a mystery.

  • HTTP Basic authentication sends a user name and password, base64-encoded, in the Authorization header; the server asks for it with a 401 and WWW-Authenticate: Basic.
  • auth().basic(..) is challenged: it sends credentials only after a challenge, which costs a second request.
  • Challenged Basic fails against servers that never challenge, such as endpoints that answer 404 to hide themselves.
  • auth().preemptive().basic(..) sends credentials with the first request, which is what APIs usually need.
  • Test the challenge, the right credentials and the wrong ones, and keep Basic credentials on HTTPS and out of logs.

Here are the commands you used in this guide:

1
2
3
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-07 -Dtest=BasicAuthenticationTest

What’s Next

Next: continue with Get and Send OAuth 2.0 Bearer Tokens in REST Assured, which gets tokens with the client credentials grant and sends them as bearer tokens.

The code:

Go deeper:

Related guides:

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