Post

Keep Credentials Off Cross-Origin Redirects in REST Assured

See how REST Assured 6.1 and later drop the Authorization and Cookie headers when a redirect leads to another origin, test that a token doesn't leak to a partner server, and turn the old behaviour back on when you must.

Keep Credentials Off Cross-Origin Redirects in REST Assured

The bank’s API answers one of its requests with a redirect to a partner server, and the test client follows it, as clients do. But what does it send to the partner? Until REST Assured 6.1, the answer was everything the original request carried: the Authorization header with the bearer token, and the session cookie. Whoever ran the partner server received a valid credential for the bank’s API. Browsers stopped doing that long ago, and REST Assured now behaves the same way. In this guide, you’ll prove the credentials stay behind, and turn the old behaviour back on for the one case that needs it.

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

What You’ll Build

You’ll build a test class called CredentialsOnRedirectTest with two tests. One sends a token and a session cookie through a redirect to another origin, and checks that neither arrives. The other turns stripping off, and checks that the token arrives.

The request is redirected to a partner on another port, and the partner reports what it received:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET /api/v1/partner-redirect HTTP/1.1
Host: localhost:<api-port>
Authorization: Bearer a-secret-token
Cookie: SESSION=a-secret-session

HTTP/1.1 302 Temporary Redirect
Location: http://localhost:<partner-port>/partner/echo-credentials

GET /partner/echo-credentials HTTP/1.1
Host: localhost:<partner-port>

HTTP/1.1 200 OK

{"authorizationReceived":false,"cookieReceived":false}

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

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

In this guide, you will:

  • See credentials dropped on a cross-origin redirect.
  • Turn the old behaviour back on for a trusted partner.

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 CredentialsOnRedirectTest in a new section_06 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (CredentialsOnRedirectTest.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 HTTP Basic Authentication in REST Assured.

Out of scope: this guide covers the test client’s credentials. It doesn’t cover how your application’s own HTTP client handles redirects, though the same question applies there.

Understand Credentials on Redirects

The problem. A redirect hands the next request to whatever server the Location header names. If the client copies every header across, a token meant for one server reaches another, and a redirect from a compromised or careless endpoint becomes a way to collect credentials. A test that only checks the final 200 passes whether the token leaked or not.

The concept. An origin is the combination of scheme, host and port, such as https://bank.example:443. Two URLs have the same origin only if all three match, so each of these redirects crosses to another origin:

FromToWhat changed
http://localhost:8080http://localhost:9090The port
https://bank.examplehttps://partner.exampleThe host
https://bank.examplehttp://bank.exampleThe scheme

Since REST Assured 6.1, when a followed redirect crosses to another origin, the Authorization and Cookie headers are dropped. RedirectConfig.stripSensitiveHeadersOnCrossHostRedirect(..) controls it, and it’s true by default. A redirect within the same origin keeps both headers.

When to use each. Keep the default in every test. Turn stripping off only for a request to a partner you trust with the credentials, such as two of your own services on different ports that share a token, and set it on that request, not globally.

Test what the redirect target received, not only that the redirect worked.

Meet the API Under Test

BankAuthApi runs the bank’s API on one port, and a partner server on another:

RequestResponse
GET /api/v1/partner-redirect on the bank302 with a Location on the partner server
GET /partner/echo-credentials on the partner{"authorizationReceived":..,"cookieReceived":..}

The partner doesn’t check the credentials; it reports whether they arrived. That makes it a witness: a test can ask it what crossed the redirect.

Your tests check these values:

  • The status 200, which proves the redirect was followed to the partner.
  • authorizationReceived, whether the Authorization header arrived.
  • cookieReceived, whether the SESSION cookie arrived.

See the Credentials Dropped

Set Up the Test Class

Goal: create the test class with the API and a helper that sends a token and a session cookie.

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

import static io.restassured.RestAssured.given;
import static io.restassured.config.RedirectConfig.redirectConfig;
import static io.restassured.config.RestAssuredConfig.config;
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 CredentialsOnRedirectTest {

    private static BankAuthApi api;

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

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

    private static RequestSpecification withCredentials() {
        return given().baseUri(api.baseUri()).port(api.port())
            .auth().oauth2("a-secret-token")
            .cookie("SESSION", "a-secret-session");
    }
}

What’s happening:

  • BankAuthApi.start() starts the bank’s API and the partner server, each on a free port.
  • withCredentials() adds a bearer token with auth().oauth2(..), and a session cookie with cookie(..): the two credentials REST Assured protects.

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

Send Credentials Through the Redirect

Goal: follow the redirect to the partner, and prove that neither credential arrived.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void credentialsAreDroppedOnACrossOriginRedirect() {
    withCredentials()
    .when()
        .get("/api/v1/partner-redirect")
    .then()
        .statusCode(200)
        .body("authorizationReceived", equalTo(false))
        .body("cookieReceived", equalTo(false));
}

What’s happening:

  • REST Assured follows the 302, as it does for every GET, so the 200 and the body come from the partner.
  • The Location is on a different port, so a different origin, and REST Assured drops Authorization and Cookie before sending the second request.
  • The partner reports that neither arrived: the bank’s credentials stayed with the bank.

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

Only Authorization and Cookie are dropped. In a check against a second server on another port, a custom X-API-Key header followed the redirect, while the token and the cookie didn’t. If your API uses a custom secret header, test what reaches the redirect target, and don’t count on REST Assured to remove it.

Turn the Old Behaviour Back On

Send the Token to a Trusted Partner

Goal: turn stripping off for one request, and prove the token now arrives.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
@Test
void theOldBehaviourCanBeTurnedBackOn() {
    // Only for a partner you trust with the credentials; the default is the safe choice.
    withCredentials()
        .config(config().redirect(redirectConfig().stripSensitiveHeadersOnCrossHostRedirect(false)))
    .when()
        .get("/api/v1/partner-redirect")
    .then()
        .statusCode(200)
        .body("authorizationReceived", equalTo(true));
}

What’s happening:

  • redirectConfig().stripSensitiveHeadersOnCrossHostRedirect(false) restores the behaviour from before REST Assured 6.1, for this request only.
  • The token arrives at the partner, and so does the cookie.
  • The other test in the class still uses the default, so it still proves the protection.

Checkpoint: run the class again. Both tests pass.

Don’t turn stripping off in RestAssured.config or a shared request specification. Every redirect in the suite would then send credentials to any server it pointed at. Set it on the one request that needs it.

After upgrading to REST Assured 6.1 or later, a test that relied on credentials following a redirect starts failing with a 401 from the second server. That’s the protection at work, not a bug in the server. Decide whether the target should get the credentials before you turn stripping off.

Run the Tests

Run the following command from the repository root:

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

You should see a result similar to the following:

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

Make a Test Fail

In theOldBehaviourCanBeTurnedBackOn, delete the .config(config().redirect(..)) line and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   CredentialsOnRedirectTest.theOldBehaviourCanBeTurnedBackOn:63 1 expectation failed.
JSON path authorizationReceived doesn't match.
Expected: <true>
  Actual: <false>

Without the configuration, the default applies, and REST Assured drops the token at the redirect. The test still gets a 200, because the partner answers either way, so only the body shows the difference. That’s why the tests check what the partner received, and not only the status.

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

Troubleshooting

SymptomLikely causeFix
A 401 from the redirect target after upgrading to REST Assured 6.1The token was dropped on purpose at a cross-origin redirectDecide whether the target should get it; if so, turn stripping off for that request
The credentials still arrive on a redirectThe redirect stays within the same origin, or stripping is off in a shared configurationCheck the Location’s scheme, host and port, and the configuration the request uses
A custom secret header reaches the redirect targetOnly Authorization and Cookie are strippedDon’t follow the redirect, or check what the target received
The test can’t see the redirect at allRedirects are followed, so the response is the target’sTurn following off with redirects().follow(false)

Try It Yourself

Exercise 1: Check the Redirect Itself

Add a test called theRedirectLeadsToAnotherOrigin. Turn following off, and check that the API answers 302 with a Location that starts with http://localhost:, ends with /partner/echo-credentials, and isn’t on the API’s own port.

Hint

Use redirects().follow(false) before when(). Combine startsWith(..), endsWith(..) and not(containsString(..)) with allOf(..), and build the port to exclude from ":" + api.port() + "/".

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void theRedirectLeadsToAnotherOrigin() {
    withCredentials()
        .redirects().follow(false)
    .when()
        .get("/api/v1/partner-redirect")
    .then()
        .statusCode(302)
        .header("Location", allOf(
                startsWith("http://localhost:"),
                endsWith("/partner/echo-credentials"),
                not(containsString(":" + api.port() + "/"))));
}

Add these imports to the class:

1
2
3
4
5
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;

Exercise 2: Check Both Credentials Both Ways

Add a test called bothCredentialsFollowOnlyWhenStrippingIsOff. With stripping off, check that both authorizationReceived and cookieReceived are true. Then, in the same test, send the same request with the default configuration, and check that both are false.

Hint

Reuse the .config(..) line from theOldBehaviourCanBeTurnedBackOn for the first request, and leave it out of the second. Each request starts from withCredentials(), so the configuration doesn’t carry over.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void bothCredentialsFollowOnlyWhenStrippingIsOff() {
    withCredentials()
        .config(config().redirect(redirectConfig().stripSensitiveHeadersOnCrossHostRedirect(false)))
    .when()
        .get("/api/v1/partner-redirect")
    .then()
        .statusCode(200)
        .body("authorizationReceived", equalTo(true))
        .body("cookieReceived", equalTo(true));

    withCredentials()
    .when()
        .get("/api/v1/partner-redirect")
    .then()
        .body("authorizationReceived", equalTo(false))
        .body("cookieReceived", equalTo(false));
}

Summary

You built CredentialsOnRedirectTest, which sends a token and a session cookie through a redirect to a partner on another origin, proves neither arrives, and turns the old behaviour back on for one request. The bank’s credentials stay with the bank unless a test says otherwise.

  • An origin is the scheme, host and port together; a change in any of them is a cross-origin redirect.
  • Since REST Assured 6.1, a followed cross-origin redirect drops the Authorization and Cookie headers, as browsers do.
  • redirectConfig().stripSensitiveHeadersOnCrossHostRedirect(false) restores the old behaviour; set it per request, for a trusted partner only.
  • Custom secret headers, such as X-API-Key, aren’t stripped.
  • Check what the redirect target received, because the final 200 looks the same either way.

Here are the commands you used in this guide:

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

What’s Next

Next: you’ve finished Module 7. Continue with Module 8: Filters and Extensibility, starting with Write Request and Response Filters in REST Assured, which shows how to inspect and change every request and response in one place.

The code:

Go deeper:

Related guides:

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