Write Negative Security Tests for OAuth 2.0 in REST Assured
Test what must happen when credentials are missing, wrong or not enough, covering the token endpoint errors of RFC 6749, the WWW-Authenticate responses of RFC 6750, expired, wrong-audience and tampered tokens, and a missing scope.
A release of the bank’s resource server stops checking when a token expires. Every test in the suite still passes, because every test sends a fresh, valid token: they all prove that the right token opens the door, and none proves that the wrong one keeps it shut. In this guide, you’ll write negative security tests that send missing, wrong and insufficient credentials on purpose, and check that the API refuses each one in the way the OAuth 2.0 standards define.
Level: Advanced · Time: 25 minutes · Part of: Module 7: Authentication and Transport Security, section 3
What You’ll Build
You’ll build a test class called NegativeSecurityTest with ten tests, grouped in two nested classes. TokenEndpoint checks what the authorization server refuses; ResourceServer checks what the API refuses: a missing token on every endpoint, an expired, wrong-audience and tampered token, and a token without the scope, with one positive control.
One of the tests sends an expired token and checks the refusal:
1
2
3
4
5
6
7
GET /api/v1/accounts HTTP/1.1
Host: localhost:<port>
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="accounts-api", error="invalid_token", error_description="The token has expired"
Content-type: application/problem+json; charset=utf-8
When you’re done, Maven reports ten passing tests:
1
2
[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Test the token endpoint’s errors.
- Reject requests without a token.
- Reject bad tokens.
- Test the scope.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can get and send bearer tokens and decode their claims, as taught in Get and Send OAuth 2.0 Bearer Tokens in REST Assured, and send a method by name, from Send Every HTTP Method in REST Assured. You should know JUnit’s
@Nestedand@ParameterizedTest.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
NegativeSecurityTestin a newsection_03package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
NegativeSecurityTest.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 doesn’t cover sessions and CSRF, or tokens from a real identity provider; they’re taught in section 4 and Module 12.
Understand Negative Security Tests
The problem. Most security bugs live in the paths a happy-path test never takes: an endpoint someone forgot to protect, a check that ignores the expiry time, a resource server that accepts tokens meant for another API, a signature that’s never verified. None of these break a single happy-path test. Only tests that send the wrong thing on purpose find them.
The concept. The OAuth 2.0 standards define the errors, so a client can tell “get a new token” from “ask for more access”:
| Situation | Status | WWW-Authenticate or body |
|---|---|---|
| Token endpoint: wrong client secret | 401 | {"error":"invalid_client"} and a Basic challenge |
| Token endpoint: unsupported grant | 400 | {"error":"unsupported_grant_type"} |
| Token endpoint: scope the client may not have | 400 | {"error":"invalid_scope"} |
| API: no token | 401 | Bearer realm="..", with no error code |
| API: expired, wrong-audience or tampered token | 401 | Bearer realm="..", error="invalid_token", error_description=".." |
| API: valid token without the scope | 403 | Bearer realm="..", error="insufficient_scope", scope=".." |
The first three come from RFC 6749, section 5.2, the last three from RFC 6750, section 3. The difference between 401 and 403 matters: 401 means “I don’t know who you are”, so the client should get a new token; 403 means “I know who you are, but you may not do this”, so a new token with the same scopes won’t help.
When to use it. Write a negative test for every check the server makes, and test each check on its own, with a token that fails exactly that one. Cover every endpoint for a missing token, and keep a positive control, so the negative tests can’t all pass because everything fails.
Prove that the wrong key keeps the door shut, one lock at a time.
Meet the API Under Test
The tests use the bank’s authorization server and resource server from the previous sections:
| Endpoint | Needs |
|---|---|
POST /oauth2/token | Client credentials, grant_type=client_credentials |
GET /api/v1/accounts | A token with accounts:read, audience accounts-api |
POST /api/v1/payments | A token with payments:write, audience accounts-api |
The resource server checks a token’s signature, expiry, audience and scope. To test each check, the tests need tokens that fail exactly one of them, and the test API has a helper for that:
1
String expired = api.mintToken("tpp-accounts", List.of("accounts:read"), BankAuthApi.AUDIENCE, Duration.ofMinutes(-1));
mintToken(client, scopes, audience, lifetime) signs a token with the server’s real key, so everything about it is valid except what the test changes. A negative lifetime gives a token that has already expired. Real authorization servers don’t offer such a helper, but a test double or a test realm can.
Every refusal by the resource server also comes with an RFC 9457 problem body whose detail repeats the reason, such as The token has expired.
Your tests check these values:
- The status of every refusal:
400,401or403. - The
errorin the token endpoint’s body. - The
WWW-Authenticateheader of the resource server, which says why it refused.
Test the Token Endpoint’s Errors
Set Up the Test Class
Goal: create the test class with two nested classes, one per server.
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
package com.javanibble.module_07.section_03;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import com.javanibble.auth.BankAuthApi;
import io.restassured.http.Method;
import io.restassured.specification.RequestSpecification;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class NegativeSecurityTest {
private static final String REALM = "Bearer realm=\"accounts-api\"";
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());
}
@Nested
class TokenEndpoint {
}
@Nested
class ResourceServer {
}
}
What’s happening:
REALMis the start of everyWWW-Authenticateheader the resource server sends.@Nestedgroups the tests by server; both nested classes share the outer class’s API, and each shows up as its own group in the report.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Send a Wrong Client Secret
Goal: check that the token endpoint refuses a wrong secret with invalid_client.
Add this test to TokenEndpoint:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void wrongClientSecret() {
bank()
.auth().preemptive().basic("tpp-accounts", "not-the-secret")
.formParam("grant_type", "client_credentials")
.when()
.post("/oauth2/token")
.then()
.statusCode(401)
.header("WWW-Authenticate", startsWith("Basic"))
.body("error", equalTo("invalid_client"));
}
What’s happening:
- The body is
{"error":"invalid_client","error_description":"Client authentication failed"}, with aBasic realm="token"challenge. - Note what it doesn’t say: whether the client id or the secret was wrong. Telling them apart would help an attacker guess client ids.
Checkpoint: run NegativeSecurityTest from your IDE. One test runs and passes.
Ask for an Unsupported Grant and a Scope Not Allowed
Goal: check two more refusals of the token endpoint.
Add these tests to TokenEndpoint:
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
@Test
void aGrantTypeTheServerDoesNotSupport() {
bank()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "password")
.formParam("username", "anna")
.formParam("password", "secret")
.when()
.post("/oauth2/token")
.then()
.statusCode(400)
.body("error", equalTo("unsupported_grant_type"));
}
@Test
void aScopeTheClientMayNotHave() {
bank()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "client_credentials")
.formParam("scope", "payments:write")
.when()
.post("/oauth2/token")
.then()
.statusCode(400)
.body("error", equalTo("invalid_scope"));
}
What’s happening:
- The first test asks for the resource owner password grant, which OAuth 2.1 leaves out because the client sees the user’s password. The server answers
unsupported_grant_type, withOnly client_credentials is supported. - The second asks for a scope
tpp-accountsmay not have, and getsinvalid_scope. - A server that refuses the password grant, and a client that can’t ask for more than it was given, are both security properties worth a test.
Checkpoint: run the class again. Three tests pass.
Reject Requests Without a Token
Cover Every Endpoint With One Test
Goal: check that every protected endpoint refuses a request without a token.
Add this test to ResourceServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
@ParameterizedTest(name = "{0} {1} needs a token")
@CsvSource({
"GET, /api/v1/accounts",
"POST, /api/v1/payments",
})
void everyEndpointRejectsAMissingToken(Method method, String path) {
bank()
.when()
.request(method, path)
.then()
.statusCode(401)
.header("WWW-Authenticate", equalTo(REALM));
}
What’s happening:
@ParameterizedTestruns the method once per@CsvSourcerow. JUnit convertsGETandPOSTto REST Assured’sMethodenum, andrequest(method, path)sends it.- RFC 6750 says that a request without a token gets no error code, only the realm: the client hasn’t done anything wrong yet; it hasn’t authenticated. So the header must be exactly
Bearer realm="accounts-api".
Checkpoint: run the class again. Five tests pass: the parameterized test shows up as one test per endpoint.
Add a row for every new endpoint. A parameterized “every endpoint needs a token” test only helps if every endpoint is in it, and then an endpoint that someone forgot to protect fails here.
Reject Bad Tokens
Send an Expired Token
Goal: check that a token that expired a minute ago is refused, for that reason.
Add this test to ResourceServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void anExpiredToken() {
String expired = api.mintToken("tpp-accounts", List.of("accounts:read"), BankAuthApi.AUDIENCE, Duration.ofMinutes(-1));
bank()
.auth().oauth2(expired)
.when()
.get("/api/v1/accounts")
.then()
.statusCode(401)
.header("WWW-Authenticate", allOf(startsWith(REALM), containsString("error=\"invalid_token\""),
containsString("expired")));
}
What’s happening:
- Only the token’s expiry is wrong.
- The full header is
Bearer realm="accounts-api", error="invalid_token", error_description="The token has expired", andallOf(..)checks its three parts.
Checkpoint: run the class again. Six tests pass.
Send a Token for Another Audience
Goal: check that a token issued for another API is refused.
Add this test to ResourceServer:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aTokenForAnotherAudience() {
String forPayments = api.mintToken("tpp-accounts", List.of("accounts:read"), "payments-api", Duration.ofMinutes(5));
bank()
.auth().oauth2(forPayments)
.when()
.get("/api/v1/accounts")
.then()
.statusCode(401)
.header("WWW-Authenticate", containsString("another audience"));
}
What’s happening:
- The token is signed, current and has the right scope, but it was issued for
payments-api. - The server answers
error_description="The token is meant for another audience". - Without the audience check, a token stolen from one API would open every API that trusts the same authorization server.
Checkpoint: run the class again. Seven tests pass.
Send a Tampered Token
Goal: check that a token whose claims were edited is refused, because its signature no longer matches.
Add this test to ResourceServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aTamperedToken() {
String token = api.mintToken("tpp-accounts", List.of("accounts:read"), BankAuthApi.AUDIENCE, Duration.ofMinutes(5));
String[] parts = token.split("\\.");
String claims = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8)
.replace("accounts:read", "payments:write");
String tampered = parts[0] + "." + Base64.getUrlEncoder().withoutPadding()
.encodeToString(claims.getBytes(StandardCharsets.UTF_8)) + "." + parts[2];
bank()
.auth().oauth2(tampered)
.when()
.post("/api/v1/payments")
.then()
.statusCode(401)
.header("WWW-Authenticate", containsString("signature is invalid"));
}
What’s happening:
- The test grants itself
payments:writeby editing the claims, and keeps the original signature. - A server that only decoded the token would let this payment through; this one verifies the signature, and refuses with
error_description="The signature is invalid".
Checkpoint: run the class again. Eight tests pass.
A refusal for the wrong reason is still a bug. A
401for an expired token and a401for a missing one are different situations, so check theWWW-Authenticateheader as well as the status, and the test fails when the server refuses for a reason it shouldn’t.
Test the Scope
Send a Valid Token Without the Scope
Goal: check that an authenticated client without the scope gets 403, not 401.
Add this test to ResourceServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aValidTokenWithoutTheScope() {
String readOnly = api.mintToken("tpp-accounts", List.of("accounts:read"), BankAuthApi.AUDIENCE, Duration.ofMinutes(5));
bank()
.auth().oauth2(readOnly)
.when()
.post("/api/v1/payments")
.then()
.statusCode(403)
.header("WWW-Authenticate", allOf(containsString("error=\"insufficient_scope\""),
containsString("scope=\"payments:write\"")));
}
What’s happening:
- The token is valid but lacks
payments:write. - The header names the scope that’s needed:
Bearer realm="accounts-api", error="insufficient_scope", scope="payments:write". A client can use it to ask for the right access.
Checkpoint: run the class again. Nine tests pass.
Test that a missing scope gives
403. A client that gets401for it will fetch a new token, get the same scopes, and loop.
Keep a Positive Control
Goal: prove that the right scope opens the door, so the 403 above was caused by the scope.
Add this test to ResourceServer:
1
2
3
4
5
6
@Test
void theRightScopeOpensTheDoor() {
String payments = api.mintToken("tpp-payments", List.of("payments:write"), BankAuthApi.AUDIENCE, Duration.ofMinutes(5));
bank().auth().oauth2(payments).when().post("/api/v1/payments").then().statusCode(201);
}
What’s happening:
- The token has the scope the payment needs, and the API creates it with
201. - This positive test belongs with the negative ones: if every request failed, every negative test would pass, and only this one would notice.
Checkpoint: run the class again. All ten tests pass.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-07 -Dtest=NegativeSecurityTest
You should see a result similar to the following, with one line per nested class:
1
2
3
4
5
6
7
8
9
[INFO] Running com.javanibble.module_07.section_03.NegativeSecurityTest
[INFO] Running com.javanibble.module_07.section_03.NegativeSecurityTest$ResourceServer
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.163 s -- in com.javanibble.module_07.section_03.NegativeSecurityTest$ResourceServer
[INFO] Running com.javanibble.module_07.section_03.NegativeSecurityTest$TokenEndpoint
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.218 s -- in com.javanibble.module_07.section_03.NegativeSecurityTest$TokenEndpoint
[INFO]
[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In aValidTokenWithoutTheScope, change statusCode(403) to statusCode(401) and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] NegativeSecurityTest.aValidTokenWithoutTheScope 1 expectation failed.
Expected status code <401> but was <403>.
The server is right and the expectation is wrong: an authenticated client without the scope gets 403. This is the confusion the 401/403 distinction exists to prevent, so a test that expects the wrong one fails, as it should.
Change statusCode(401) back to statusCode(403) and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected status code <401> but was <403> | The token is valid but lacks the scope | Expect 403 with insufficient_scope |
A missing-token test gets a header with error=.. | The request sent a token after all | Check that the request has no auth() or Authorization header |
A tampered-token test passes with 201 | The server doesn’t verify signatures | Fix the server: decoding a token isn’t validating it |
| Every negative test passes, and so does a broken build | Every request fails for an unrelated reason | Add a positive control, such as theRightScopeOpensTheDoor |
Try It Yourself
Exercise 1: Don’t Reveal Which Credential Was Wrong
Add a test to TokenEndpoint called anUnknownClientLooksLikeAWrongSecret. Request a token once with an unknown client id, tpp-unknown, and the right-looking secret, and once with the right client id and a wrong secret. Check that the first gets 401 with invalid_client, and that both responses have the same status, the same WWW-Authenticate header and the same body.
Hint
Keep both responses as Response objects, as in Take Apart a REST Assured Test, and compare them with JUnit’s assertEquals(..). asString() returns the body as text.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void anUnknownClientLooksLikeAWrongSecret() {
Response unknownClient = bank()
.auth().preemptive().basic("tpp-unknown", "accounts-secret")
.formParam("grant_type", "client_credentials")
.when()
.post("/oauth2/token");
Response wrongSecret = bank()
.auth().preemptive().basic("tpp-accounts", "not-the-secret")
.formParam("grant_type", "client_credentials")
.when()
.post("/oauth2/token");
unknownClient.then().statusCode(401).body("error", equalTo("invalid_client"));
assertEquals(wrongSecret.statusCode(), unknownClient.statusCode());
assertEquals(wrongSecret.header("WWW-Authenticate"), unknownClient.header("WWW-Authenticate"));
assertEquals(wrongSecret.asString(), unknownClient.asString());
}
Add imports for io.restassured.response.Response and assertEquals to the class.
Exercise 2: Refuse an Unsigned Token
A classic JWT attack replaces the algorithm in the header with none and drops the signature. Add a test to ResourceServer called anUnsignedTokenIsRefused. Mint a valid payments:write token, build an unsigned copy with the header {"alg":"none","typ":"at+jwt"}, the same claims and an empty signature, and check that a payment with it gets 401 with error="invalid_token". Then check, as a positive control, that the original token creates the payment.
Hint
Encode the new header with Base64.getUrlEncoder().withoutPadding(), as aTamperedToken encodes the claims, and join the parts as header + "." + claims + ".". The server answers The token is not a JWS.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void anUnsignedTokenIsRefused() {
String token = api.mintToken("tpp-payments", List.of("payments:write"), BankAuthApi.AUDIENCE, Duration.ofMinutes(5));
String header = Base64.getUrlEncoder().withoutPadding()
.encodeToString("{\"alg\":\"none\",\"typ\":\"at+jwt\"}".getBytes(StandardCharsets.UTF_8));
String unsigned = header + "." + token.split("\\.")[1] + ".";
bank()
.auth().oauth2(unsigned)
.when()
.post("/api/v1/payments")
.then()
.statusCode(401)
.header("WWW-Authenticate", allOf(startsWith(REALM), containsString("error=\"invalid_token\"")));
bank().auth().oauth2(token).when().post("/api/v1/payments").then().statusCode(201);
}
Summary
You built NegativeSecurityTest, which checks the token endpoint’s errors, a missing token on every endpoint, expired, wrong-audience and tampered tokens, and a missing scope, with a positive control. A resource server that stops checking expiry now fails a test.
- Negative security tests check what happens when credentials are missing, wrong or not enough, which is where most security bugs are.
- At the token endpoint, RFC 6749 defines
invalid_client,unsupported_grant_typeandinvalid_scope. - At the resource server, RFC 6750 defines a bare
Bearer realmfor a missing token,401witherror="invalid_token"for a bad one, and403witherror="insufficient_scope"for a missing scope. - Mint tokens that fail one check each, and check
WWW-Authenticateas well as the status, so a refusal for the wrong reason fails. - Cover every endpoint with a parameterized test, and keep a positive control.
Here are the commands you used in this guide:
1
mvn test -pl module-07 -Dtest=NegativeSecurityTest
What’s Next
Next: continue with Test a Session Login With CSRF in REST Assured, which logs in through a form with a CSRF token and keeps the session cookie.
The code:
- The finished test class:
NegativeSecurityTest.java - The code and run commands for this module: Module 7 README
Go deeper:
- RFC 6749, section 5.2: Error Response, for the token endpoint’s errors.
- RFC 6750, section 3: The WWW-Authenticate Response Header Field, for the resource server’s errors.
- OWASP JSON Web Token Cheat Sheet, for attacks such as
alg: noneand how to prevent them.
Related guides:
- Get and Send OAuth 2.0 Bearer Tokens in REST Assured, for the tokens these tests break on purpose.
- Check Session Cookie Security in REST Assured, for another security test that goes beyond the happy path.
