Java developer comparing Authorization headers received by the original server and a different origin after an HttpClient redirect.

Java HttpClient Followed a Redirect. Which Headers Reached the New Origin?

Tue, Nov 17, 2026

When an application uses java.net.http.HttpClient to follow a 3xx redirect, does it securely handle sensitive headers? By default, HttpClient uses Redirect.NEVER; automatic redirects must be enabled explicitly. When automatic redirection occurs, 301 and 302 responses convert a POST request to GET. RFC 9110 advises considering removal of caller-added Authorization headers where redirecting them has security implications. In practice, an “automatic success” (for example, the client getting a 200 OK after redirect) can be misleading if the underlying request actually dropped its auth credentials.

Our goal is to define a precise acceptance test: the HTTP client should follow the 3xx redirect (on the same protocol to avoid policy blocks) and then we will capture the actual headers received by the new origin.

The planned tests use fixed inputs (a synthetic Authorization token, fixed URIs) and require fully isolated servers. We independently specify the expected outcome (Authorization not forwarded across origins), then run the scenarios to collect evidence. The sample logs and results below are illustrative: EXPECTED / NOT EXECUTED. Only if the observed behavior matches our acceptance contract (drop the header on cross-origin redirect) can we ACCEPT. Otherwise we will propose a REPAIR (manual header removal or alternative logic), then RERUN and gate this in. Handle fixture teardown and thread shutdown carefully, using explicit executor shutdown.

1. Define the Operational Acceptance Contract

The first step is to define exactly what “correct” behavior means. In our case, the contract is:

  • Given: A Java 21 HttpClient configured to follow redirects (Redirect.ALWAYS or NORMAL), sending an Authorization header and any other fixed headers.

  • When: The client receives a 3xx response with a Location pointing to a (different) origin.

  • Then: The redirected request should not contain the original Authorization (and similar credentials) if the origin changed. Other stable headers (like custom X-headers) are allowed.

  • Pass/Fail: If the new origin’s request contains the Authorization header, the test fails (safety violation); if it is absent, we mark SUCCESS (the outcome required by our acceptance contract). We also define a negative control: with followRedirects(NEVER) the client should not follow at all, so no second request. Evidence artifacts include the raw request/response traces for each origin.

We express this contract with an automated test: a first server that returns a 307 (Temporary Redirect) with a Location, and a second server that logs incoming requests. This setup uses separate threads (or executors) so that each HTTP exchange is isolated, and we must explicitly shut down the thread pool afterward (cf. Python executor shutdown). Our assertion is ultimately on the logged headers at the second server. If they match our expected manifest (no Authorization), we ACCEPT; if not, we consider a fix.

2. Establish a Versioned Baseline

We must pin down environment details precisely. The example baseline is Ubuntu 22.04 LTS x86_64 with an Oracle JDK or OpenJDK 21 runtime, such as 21.0.0. Record the exact vendor and java -version output before execution. Label the fixture revision v1.0.0 and retain the exact code used. This baseline is critical: different Java versions or JVM vendors could theoretically change behavior. We compile and run with exact imports: e.g. import java.net.http.HttpClient; import java.net.http.HttpRequest; etc, all from Java SE 21. We assume no additional HTTP libraries (to isolate only java.net.http.HttpClient).

Pinned inputs: The Authorization token string is synthetic (e.g. Bearer test-token). The server URIs use HTTP on 127.0.0.1, with port 8000 and path /redirect for the initial request, and port 8001 and path /final for the Location redirect target (ensuring host is same but port differs, i.e. a different origin by scheme/host/port rules). We also log the Host and full request target. A key boundary condition: test on HTTP→HTTP so the explicitly selected policy NORMAL will follow (per its rule: “except from HTTPS to HTTP”). If the redirect were HTTPS→HTTP, NORMAL would not follow, which is a separate boundary case. Pass/fail criterion: For each run, we verify the HTTP status at each step (200 at final for follow, or 3xx for no-follow) and that captured headers align with expected. Mismatches will appear as failures to accept.

Pin the Environment and Inputs

  • Runtime: Java 21 (21.0.x family), Oracle JDK or OpenJDK on Ubuntu 22.04, x86_64. Record the exact build before execution.

  • HTTP Protocol: HTTP/1.1 (no TLS) for both client and servers.

  • Ports: 8000 for origin, 8001 for redirect target.

  • Redirect policy: We test HttpClient.Redirect.ALWAYS explicitly (though NORMAL acts the same here since protocol doesn't downgrade).

  • Request template: GET /redirect HTTP/1.1 with headers including Authorization: Bearer test-token, and a custom header X-Test: case1.

  • Location header: an HTTP URL for 127.0.0.1 on port 8001, with path /final.

  • Criterion: The redirected request to port 8001 at /final must not have Authorization. If it does, fail.

By fixing these details, we eliminate ambiguity: only the code-under-test varies (redirect enabled vs disabled), while OS, JDK, and inputs are constants.

3. Build an Isolated Disposable Fixture

The following Java 21 example sketches two HTTP servers for the origin and redirect target. Execution status: EXPECTED / NOT EXECUTED.

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpExchange;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
import java.io.IOException;
import java.util.concurrent.Executors;

public class RedirectTestFixture {
    public static void main(String[] args) throws Exception {
        HttpServer origin = HttpServer.create(new InetSocketAddress(8000), 0);
        origin.createContext("/redirect", (HttpExchange ex) -> {
            // Log and respond with 307
            System.out.println("Origin received: " + ex.getRequestURI()
                + " Headers: " + ex.getRequestHeaders());
            ex.getResponseHeaders().add(
                "Location", "http://127.0.0.1:8001/final");
            ex.sendResponseHeaders(307, -1);
            ex.close();
        });
        HttpServer target = HttpServer.create(new InetSocketAddress(8001), 0);
        target.createContext("/final", (HttpExchange ex) -> {
            System.out.println("Target received: " + ex.getRequestURI()
                + " Headers: " + ex.getRequestHeaders());
            // Echo or simple 200 OK
            ex.sendResponseHeaders(200, 0);
            ex.getResponseBody().write("OK".getBytes());
            ex.close();
        });
        origin.setExecutor(Executors.newSingleThreadExecutor());
        target.setExecutor(Executors.newSingleThreadExecutor());
        origin.start();
        target.start();

        // Make the client request
        HttpClient client = HttpClient.newBuilder()
            .followRedirects(HttpClient.Redirect.ALWAYS)
            .build();
        HttpRequest req = HttpRequest.newBuilder(
                new URI("http://127.0.0.1:8000/redirect"))
            .header("Authorization", "Bearer test-token")
            .GET()
            .build();
        HttpResponse<String> resp = client.send(
            req, HttpResponse.BodyHandlers.ofString());
        System.out.println("Client got: " + resp.statusCode()
            + " final URI: " + resp.uri());

        // Cleanup
        origin.stop(0);
        target.stop(0);
    }
}

In this fixture, the origin is intended to log incoming requests, including the Authorization header, then reply 307 with a Location. The target is intended to log whatever it receives. Each server runs on its own executor (single thread) so it is self-contained, and we can call stop() after the client finishes. Close or stop servers explicitly, similar to graceful task shutdown in the Kubernetes preStop lifecycle, to avoid port conflicts or dangling threads. All imports shown above come from JDK 21 (no external libraries). Before using this sketch as an evidence harness, bind the servers to loopback, retain and close their executor services, log individual header entries, and send the X-Test value being checked. The sketch does not yet implement these steps.

4. Author the Independent Expected-Case Manifest

Before running tests, we document the expected outcomes in a manifest. This is done independently of observations. For each case, we define:

  • The request that is sent

  • The expected response sequence

  • The expected headers at each stage

For example:

  • Case A (False-Positive Same-Origin): If the redirect Location had pointed to 127.0.0.1:8000/final (same host/port as origin), the same-origin baseline expects HttpClient to include Authorization. Expected: Final request on 8000 would see Authorization: Bearer test-token.

  • Case B (Normal Cross-Origin Redirect): Redirect to 127.0.0.1:8001/final (different port). Expected under our acceptance contract: Final request on 8001 should not include Authorization.

  • Case C (No Redirect / Negative Control): Client configured NEVER. Expected: Client receives the 307 from origin and stops; target on 8001 is never called.

  • Case D (Repair Scenario): If a “fix” were applied (e.g. explicitly removing Authorization even on same-origin), then for Case A we would expect no auth on final (contrary to the same-origin baseline expectation). We list both documented behavior and our inferences here.

Our manifest, for clarity, can be summarized as:

Case

Setup

Redirect followed?

Expected Authorization at target

Notes

A

Same-origin (8000 → 8000)

YES

YES (Auth sent)

Not security concern, baseline

B

Cross-origin (8000 → 8001)

YES

NO (Auth dropped)

Desired behavior

C

Policy=NEVER (no redirect)

NO

n/a

Negative control

D

(After fix) treat orig as x-origin

YES

NO (Auth dropped)

Proposed repair impact

We treat Case A as a false-positive example: it would “pass” a naive test by still having auth, but it’s not the scenario we need. Case B is the actual success scenario to verify. Case C is the failing negative control (no follow). We clearly mark each case as Expected and do NOT run it yet. These expectations reflect the acceptance contract, documented redirect policies, and logical rules (none of these has been observed, thus they are all EXPECTED / NOT EXECUTED until we test).

Preserve a Failing Negative Control

The negative control (Case C) confirms our harness catches the absence of a redirect. We expect the client to see the 307 and not query the second server. A boundary check: if the client unexpectedly followed, that’s a failure. Pass criterion: second server’s log remains empty, confirming no request was made. This ensures our test can detect both the presence and absence of redirect behavior.

5. Reproduce the Misleading Success

Now we set up a scenario that might falsely indicate success. For example, if the redirect used the same port (8000 → 8000), HttpClient will consider it the same origin. In that baseline, we expect it to forward the Authorization header, making it seem like everything is fine (header reached new URI). To exercise this, configure /redirectSame to redirect to /final on the same HTTP origin, 127.0.0.1 on port 8000. Add both routes to the origin server for this case. Observing that the target sees the header would be a false-positive result: it looks like authorization forwarded, but it violated the cross-origin assumption of our contract. By comparing this with the expected manifest (Case A vs Case B), we confirm that any “success” from same-origin is not the real success criteria. We log this as a baseline: e.g.,

// Case A: same-origin redirect
HttpClient.newBuilder()
  .followRedirects(HttpClient.Redirect.ALWAYS)
  .build()
  .sendAsync(
      HttpRequest.newBuilder(
          URI.create("http://127.0.0.1:8000/redirectSame"))
          .GET()
          .header("Authorization","Bearer test-token")
          .build(),
      BodyHandlers.discarding())
  .get();

If target (port 8000) prints the header, that is expected for Case A (EXPECTED / NOT EXECUTED). It serves to validate our fixture logic (that it can forward when same origin) and contrast with the cross-origin case.

6. Run the Controlled Comparison

To perform the main test (Case B) with Redirect.ALWAYS (or NORMAL, same result here) and our servers on ports 8000→8001, execute the client request and capture logs. The controlled comparison is between expected vs actual: we compare our manifest (Auth should be NO in redirected request) with what the servers logged. For example, after running:

# Example command (EXPECTED / NOT EXECUTED):
java RedirectTestFixture

An illustrative log, using explicit per-header logging and a sample X-Test value of foo, would look like this (EXPECTED / NOT EXECUTED):

Origin received: /redirect
  Headers: [Authorization:"Bearer test-token",
            X-Test:"foo",
            Host:"127.0.0.1:8000"]
Target received: /final  
  Headers: [X-Test:"foo",
            Host:"127.0.0.1:8001"]
Client got: 200  final URI: http://127.0.0.1:8001/final

This example depicts the origin receiving Authorization and the target receiving none. The table retains those illustrative values; actual captures are still required. Status: EXPECTED / NOT EXECUTED.

Case

Status sequence

Example target headers

Expected Authorization at target

B

307 → 200

Host:127.0.0.1:8001, X-Test:foo (no Auth)

No Authorization

If captured target request headers match our expected manifest (no Authorization), the case meets that header criterion. Verify that no unexpected duplicates or missing events appear in the logs and that the invocation to /final is accounted for.

Check Missing and Duplicate Events

We ensure the logs have one request on each server. No duplicate lines should appear. A boundary: if the origin had multiple 3xx cycles or if the client retried, we would see extra entries. Confirm exactly one log entry on the origin and one on the target. If we observed zero or multiple, we would flag a failure. This satisfies the criterion that the event trace is complete and singular.

7. Exercise Negative and Boundary Cases

We broaden the tests:

  • Alternative Redirect Policy: Try Redirect.NORMAL explicitly (should match ALWAYS here) and Redirect.NEVER (should produce no second call).

  • Missing Auth: Repeat with no Authorization header; ensure nothing breaks and output has no auth (sanity check).

  • Different Methods: If our scenario used GET, we can test with a POST. The Java 21 redirect documentation specifies that 301/302 converts POST to GET when automatic redirection occurs. We include one test where the request method is POST to see that final target is still accessed (the default behavior changes to GET).

  • Protocol Boundary: Attempt an HTTPS→HTTP redirect. With NORMAL, HttpClient should not follow, acting as an effective negative control. (We mark this as a separate negative/boundary test.)

  • Error Status Handling: If the target returns 401 without auth, we see if HttpClient resends (it won’t, since we didn’t implement any authenticator).

  • Large Headers: Test with a very long Authorization value to check no truncation.

Each scenario has a pass/fail criterion. For example, in the HTTPS→HTTP case, followRedirects(NORMAL) should result in a 3xx response with no second hit (pass). If it wrongly followed, that would violate documented redirect policy. (None of these should alter our main case result.)

8. Capture Per-Case Raw Evidence

Assemble a case-by-case evidence ledger from actual captures. The following table illustrates its structure and the expected sample outcomes. All rows are EXPECTED / NOT EXECUTED:

Case

Request target

HTTP status sequence

Example final headers

Remarks

A (false pos)

127.0.0.1:8000

307 → 200

Authorization: Bearer test-token
X-Test: foo

FALSE-POSITIVE: Auth forwarded (same-origin).

B (cross origin)

127.0.0.1:8001

307 → 200

X-Test: foo (no Auth)

Would pass: Authorization dropped as expected.

C (no redirect)

127.0.0.1:8000

307 only

– (target not called)

Negative Control: No follow.

Each completed row must be built from raw logs. We compare Observed vs Expected for Authorization presence. In the illustrative rows, only Case A has Authorization in the final request, as intended in the manifest, while Case B has none. Any deviation from expected would appear here.

Retain the Evidence Before Cleanup

Before tearing down servers and client, we save all logs (console output, variables) to files. For example, redirect log files or printed statements. A failing boundary would be if any log line is truncated or missing. Validate that the origin and target logs contain the events required by the selected case. If evidence were lost, we would mark RERUN. The illustrative fixture uses console output, so retain the actual output alongside the runtime details and fixture revision to make the test reproducible.

Keep all evidence at this stage. We defer cleanup until after reconciliation.

9. Reconcile Expected and Actual State

We compare the independent manifest (Section 4) to the illustrative outcomes (Section 8). In Case B (cross-origin with redirect), the manifest expected "no Authorization" on target, and the example row shows that outcome. In Case C, we expected no target call, and the example shows none. In Case A, the manifest expected Authorization (same-origin), which matches the example (though Case A is a special scenario, not part of acceptance criteria, it serves as a sanity check). Flag any discrepancies in actual captures. If actual captures match these expectations, we can ACCEPT under this contract. The illustrative results remain EXPECTED / NOT EXECUTED.

Use a single reconciliation table. These sample entries are EXPECTED / NOT EXECUTED; PASS applies only if actual evidence confirms them:

Assertion

Expected

Example result

Decision if observed

Cross-origin redirect drops Auth

No Auth sent

No Auth

PASS

Same-origin redirect sends Auth

Auth sent

Auth sent

PASS

No-redirect policy stops at 307

No target

No target

PASS

(Additional bounds like HTTPS→HTTP)

No follow

No follow

PASS (not executed)

If all required cases pass on actual evidence, no immediate REPAIR is needed.

10. Separate Documented Behavior From Observation

Distinguish specification requirements, the acceptance contract, and actual observations. RFC 9110 separates automatically generated fields from caller-added fields: for caller-added Authorization, it advises considering removal where security implications exist. Our contract requires no Authorization at the different origin. The illustrative result shows that desired outcome, but it is EXPECTED / NOT EXECUTED. Only a captured run can establish what the selected Java 21 build did. Even a matching observation is not a guarantee for other builds or configurations. Preserve the specification’s normative wording and document any discrepancy between the contract and actual captures.

Prove the Repair Has a Bounded Effect

If we had needed a fix (e.g., if Auth had erroneously passed on cross-origin), a “repair” might be to explicitly clear the header or disable redirect. To prove minimal side effects, we would re-run the negative and other cases after applying the fix. For example, if we manually removed the Authorization in client code, we must show it doesn’t break anything else (e.g. it shouldn’t affect cookies or unrelated headers). We would rerun Case A (same-origin) to see if our change only prevented the unwanted forwarding. A test criterion: the repair should break only the narrow case where it’s intended, and retain all previously passing behaviors.

11. Repair the Narrow Failure Mode

If actual captures satisfy the contract, no repair is required for that tested case. If Authorization reaches the different origin, a narrow repair can disable automatic redirects with Redirect.NEVER, handle the 3xx response, and resend an explicitly rebuilt request without that header. However, for systems where a stricter policy is desired, we could implement in code: after a redirect response is received, create a new HttpRequest to the Location with only approved headers.

For illustration, the following pseudocode rebuilds a bodyless GET request after an absolute Location response. It assumes Redirect.NEVER was selected before the initial send. Execution status: EXPECTED / NOT EXECUTED.

if (response.statusCode() == 307) {
    URI newUri = URI.create(response.headers().firstValue("Location").get());
    HttpRequest.Builder newReq = HttpRequest.newBuilder(newUri)
        .method(response.request().method(),
            HttpRequest.BodyPublishers.noBody());
    // Copy all headers except Authorization
    response.request().headers().map().forEach((k,v) -> {
        if (!k.equalsIgnoreCase("authorization")) {
            v.forEach(val -> newReq.header(k,val));
        }
    });
    HttpResponse<String> newResp = client.send(
        newReq.build(), BodyHandlers.ofString());
    // ...
}

This pseudocode omits Authorization from the rebuilt request. Relative Location values and requests with bodies require additional handling; verify the complete request chain before accepting the repair.

12. Test Recovery, Rollback and Rerun

After any repair or configuration change, we rerun the relevant tests. For example, if we implemented the above stripping logic, we check that Case A (same-origin) now fails (demonstrating the change) while Case B still passes. We might also simulate an incident by temporarily setting followRedirects(NEVER) and then back to ALWAYS, to confirm the system recovers. One criterion is idempotency: multiple runs of the test on the same setup should yield the same acceptance result. This is akin to a PostgreSQL workload replay, where the inputs and validation rules must stay consistent. Confirm that the logs and outcomes are consistent across test runs. If any nondeterminism or new failures appear, we would RERUN after investigating. Ownership of this change would rest with the development team (see below).

Assign Ownership and Retest Criteria

For an operational team, assign a responsible engineer or group to monitor this behavior going forward (e.g. "HTTP Client Integration Team"). The retest criteria should be part of any deployment pipeline: e.g., after an upgrade of JDK or change in redirect logic, rerun these specific tests. If running in production, any actual redirect involving authentication should trigger a quick audit of logs. The pass condition for automated gates is the same as above. A boundary condition: if the redirect target changes origin in production (e.g. switching from api.internal/ to api.external/), we must rerun checks.

13. Apply the ACCEPT / REPAIR / RERUN / HOLD Matrix

Finally, we choose an action:

  • ACCEPT: All required observed behavior matches the acceptance contract. If Authorization is absent as required and the control cases pass, accept and document the tested behavior.

  • REPAIR: Would apply if we saw Auth forwarded on a cross-origin redirect. (Then we’d add logic to remove it manually.)

  • RERUN: If the test environment was flaky or partial (e.g., network glitch), we would rerun before deciding. Complete, clear logs are needed before making a decision.

  • HOLD: If we found ambiguous behavior (for example, if one run forwarded the header and another did not), we would hold action pending more investigation.

For the illustrative matching outcomes above, the verdict would be ACCEPT once actual evidence confirms them. Until execution and reconciliation are complete, HOLD the release decision; the examples remain EXPECTED / NOT EXECUTED. Keep these cases in the regression suite for future releases and archive the complete ledger, fixture code, and manifest as a readiness checkpoint.

14. Build Related Skills With Refonte Learning

Teams developing robust HTTP services can benefit from systematic testing practices like this. For example, Refonte Learning’s software engineering program covers advanced topics including networking, cloud APIs, and security, providing 3-month training at 12–14 hours/week in full-stack development, real-time data processing, optimization, and security. If you’re looking to deepen skills in building and validating production-quality integration code, consider exploring the Refonte Software Engineering Program or related courses.

These practical skills ensure that when you configure HttpClient or any HTTP library, you can define acceptance criteria, isolate test fixtures, and perform evidence-based reconciliation as shown above. In essence, rigorous test-driven validation (as outlined in this playbook) complements the knowledge one gains in focused programs like Refonte’s, closing the gap between design and operational confidence.