Get and Send OAuth 2.0 Bearer Tokens in REST Assured
Get an access token with the client credentials grant, authenticate the client with client_secret_basic or client_secret_post, send the token with auth().oauth2(..), and read the claims of a JWT access token.
Your open banking test calls the bank’s accounts API with a bearer token that someone copied from an API client into the test. It passes for five minutes, and the next morning the build is red, because the token expired overnight. In this guide, you’ll get a fresh access token in the test itself with the OAuth 2.0 client credentials grant, send it with every request, and read what the authorization server put in it.
Level: Intermediate · Time: 25 minutes · Part of: Module 7: Authentication and Transport Security, section 2
What You’ll Build
You’ll build a test class called BearerTokenTest with five tests. A helper gets a token once for the class; the tests check the token response, get a token with the other client authentication method, send the token in two ways, and read the claims of the JWT.
The helper sends this request, and keeps the token from the response:
1
2
3
4
5
6
7
8
9
10
11
12
POST /oauth2/token HTTP/1.1
Host: localhost:<port>
Authorization: Basic dHBwLWFjY291bnRzOmFjY291bnRzLXNlY3JldA==
Content-Type: application/x-www-form-urlencoded
(the form fields grant_type=client_credentials and scope=accounts:read)
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
Cache-control: no-store
{"access_token":"eyJhbGciOiJSUzI1NiIs...","token_type":"Bearer","expires_in":300,"scope":"accounts:read"}
When you’re done, Maven reports five passing tests:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Get a token with the client credentials grant.
- Send the token.
- Read the claims of a JWT.
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 send preemptive Basic, as taught in Test HTTP Basic Authentication in REST Assured, form parameters, from Send Query and Form Parameters in REST Assured, and read JSON with
JsonPath.from(..), from Read Many Values With JsonPath and XmlPath in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
BearerTokenTestin a newsection_02package next to the class from the previous section, and follow every heading below. - Skip ahead: open the finished class (
BearerTokenTest.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 what the resource server must refuse, such as expired or forged tokens and missing scopes; that’s taught in section 3.
Understand the Client Credentials Grant
The problem. Most modern APIs don’t take a password on every request. A client first gets an access token from an authorization server, then sends that token with each request. A test that hard-codes a token breaks when it expires, and can’t prove that the token endpoint works at all. To test such an API, a test has to do what a client does: get a token, then use it.
The concept. The client credentials grant, from RFC 6749, section 4.4, is OAuth 2.0 for a client acting on its own behalf, without a user:
- The client posts a form to the token endpoint, with
grant_type=client_credentialsand, optionally, thescopeit wants. Several scopes are separated by spaces. - The client authenticates itself, either with HTTP Basic (
client_secret_basic, which RFC 6749 prefers) or withclient_idandclient_secretform parameters (client_secret_post). - The server answers with an access token, its type, its lifetime and the scopes it grants.
- The client sends the token as
Authorization: Bearer <token>on every API request, as RFC 6750 defines.
When to use it. Get a token in the test, once per class in @BeforeAll: getting one for every test is slow, and real authorization servers rate-limit token requests. Check the token endpoint’s own contract in one test, and send the token with auth().oauth2(..) everywhere else.
Get tokens the way a client does, once per class, and never hard-code one.
Meet the API Under Test
The tests use the bank’s API from the previous section. Its authorization server knows two clients:
| Client | Secret | Allowed scopes |
|---|---|---|
tpp-accounts | accounts-secret | accounts:read |
tpp-payments | payments-secret | accounts:read, payments:write |
POST /oauth2/token answers with a token response, as shown above. The access token is a JWT signed with RS256, valid for 300 seconds. Its header and claims decode to:
1
{"alg":"RS256","typ":"at+jwt","kid":"key-06a4040e"}
1
2
3
4
5
6
7
8
9
10
{
"iss": "http://localhost:59458",
"sub": "tpp-accounts",
"client_id": "tpp-accounts",
"aud": "accounts-api",
"scope": "accounts:read",
"iat": 1795329927,
"exp": 1795330227,
"jti": "451d8a06-123a-4eb6-bc0d-132ce378e219"
}
GET /api/v1/accounts needs a token with accounts:read and the audience accounts-api, and answers:
1
{ "client": "tpp-accounts", "accounts": [{ "id": "acc-1001", "iban": "NL91ABNA0417164300" }] }
Token errors follow RFC 6749, with an error and an error_description. Wrong client credentials give 401 with "error": "invalid_client", and a scope the client may not have gives 400 with "error": "invalid_scope".
Your tests check these values:
- The token response’s
token_type,expires_in,scopeandaccess_token, and itsCache-Controlheader. - The
clientthe accounts endpoint saw. - The JWT’s
iss,aud,client_idandscopeclaims.
Get a Token With the Client Credentials Grant
Set Up the Test Class and a Token Helper
Goal: create the test class, and get a token once, before the first test.
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
54
package com.javanibble.module_07.section_02;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.javanibble.auth.BankAuthApi;
import io.restassured.path.json.JsonPath;
import io.restassured.specification.RequestSpecification;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class BearerTokenTest {
private static final String JWT = "[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+";
private static BankAuthApi api;
private static String accountsToken;
@BeforeAll
static void startApiAndGetAToken() {
api = BankAuthApi.start();
accountsToken = clientCredentialsToken("tpp-accounts", "accounts-secret", "accounts:read");
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification bank() {
return given().baseUri(api.baseUri()).port(api.port());
}
static String clientCredentialsToken(String clientId, String secret, String scope) {
return bank()
.auth().preemptive().basic(clientId, secret)
.formParam("grant_type", "client_credentials")
.formParam("scope", scope)
.when()
.post("/oauth2/token")
.then()
.statusCode(200)
.extract().path("access_token");
}
}
What’s happening:
clientCredentialsToken(..)runs the grant withclient_secret_basic:auth().preemptive().basic(..)authenticates the client, andformParam(..)makes the request a form post.- It validates the
200before it extracts the token, as you did in Module 4. @BeforeAllgets the token once for the whole class. It lives 300 seconds, which is plenty for one class.JWTis a pattern for three base64url parts separated by dots.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Authenticate the client preemptively. Without credentials, this token endpoint answers
401with"error": "invalid_client"but noWWW-Authenticateheader, so it never challenges, and challenged Basic never sends the secret. You’ll see that failure in Make a Test Fail.
Check the Token Response
Goal: check the token endpoint’s own contract.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void theTokenResponse() {
bank()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "client_credentials")
.when()
.post("/oauth2/token")
.then()
.statusCode(200)
.header("Cache-Control", "no-store")
.body("token_type", equalTo("Bearer"))
.body("expires_in", greaterThan(0))
.body("scope", equalTo("accounts:read"))
.body("access_token", matchesPattern(JWT));
}
What’s happening:
Cache-Control: no-storeis required by RFC 6749, section 5.1, so no proxy keeps a copy of a token.- The request asks for no scope, so the server grants all the client may have:
accounts:read. matchesPattern(JWT)checks the token’s format without depending on its value.
Checkpoint: run BearerTokenTest from your IDE. One test runs and passes.
Use client_secret_post
Goal: authenticate the client with form parameters instead of Basic, and ask for two scopes.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void clientSecretPostInsteadOfBasic() {
bank()
.formParam("grant_type", "client_credentials")
.formParam("client_id", "tpp-payments")
.formParam("client_secret", "payments-secret")
.formParam("scope", "accounts:read payments:write")
.when()
.post("/oauth2/token")
.then()
.statusCode(200)
.body("scope", equalTo("accounts:read payments:write"));
}
What’s happening:
- The client credentials move from the
Authorizationheader to the form, asclient_idandclient_secret. - Several scopes are separated by spaces, as RFC 6749 defines.
Checkpoint: run the class again. Two tests pass.
Separate scopes with spaces, not commas. This server reads
"accounts:read,payments:write"as one unknown scope, and answers400with"error": "invalid_scope"andThe client may not request [accounts:read,payments:write].
Send the Token
Use auth().oauth2(..)
Goal: call the accounts API with the class’s token.
1
2
3
4
5
6
7
8
9
10
@Test
void useTheTokenWithOauth2() {
bank()
.auth().oauth2(accountsToken)
.when()
.get("/api/v1/accounts")
.then()
.statusCode(200)
.body("client", equalTo("tpp-accounts"));
}
What’s happening:
auth().oauth2(token)sendsAuthorization: Bearer <token>.- The accounts API reads the token and answers with the client it belongs to.
Checkpoint: run the class again. Three tests pass.
Send a Plain Header
Goal: send the same token as a header you write yourself.
1
2
3
4
5
6
7
8
9
@Test
void orAsAPlainHeader() {
bank()
.header("Authorization", "Bearer " + accountsToken)
.when()
.get("/api/v1/accounts")
.then()
.statusCode(200);
}
What’s happening:
- Both forms send the same header.
auth().oauth2(..)says what it means. The plain header is useful when the scheme isn’tBearer, or when a specification already builds the headers.
Checkpoint: run the class again. Four tests pass.
A bearer token is a credential: whoever holds it can use it until it expires. Keep tokens out of logs by blacklisting
Authorization, as Keep Secrets Out of REST Assured Logs shows.
Read the Claims of a JWT
Decode the Claims
Goal: check what the authorization server put in the token.
A JWT access token, as RFC 9068 defines it, is three base64url-encoded parts: a header, the claims and a signature.
1
2
3
4
5
6
7
8
9
10
@Test
void theTokenIsAJwtWhoseClaimsCanBeRead() {
String claimsJson = new String(Base64.getUrlDecoder().decode(accountsToken.split("\\.")[1]), StandardCharsets.UTF_8);
JsonPath claims = JsonPath.from(claimsJson);
assertEquals(api.issuer(), claims.getString("iss"));
assertEquals(BankAuthApi.AUDIENCE, claims.getString("aud"));
assertEquals("tpp-accounts", claims.getString("client_id"));
assertEquals("accounts:read", claims.getString("scope"));
}
What’s happening:
split("\\.")[1]takes the middle part, andBase64.getUrlDecoder()decodes it to JSON.JsonPath.from(..)reads the claims, as it read the webhook in Module 4.- The checks compare the issuer, audience, client and scope with what the server should issue.
Checkpoint: run the class again. All five tests pass.
Decoding claims isn’t validating the token. Anyone can decode a JWT, and anyone can forge one if the signature isn’t checked. Decode claims to check what was issued, never to decide whether a token is valid. Validating tokens is the resource server’s job, and section 3 tests that it does it.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-07 -Dtest=BearerTokenTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_07.section_02.BearerTokenTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.478 s -- in com.javanibble.module_07.section_02.BearerTokenTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In clientCredentialsToken(..), change .auth().preemptive().basic(clientId, secret) to .auth().basic(clientId, secret) and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Errors:
[ERROR] BearerTokenTest.startApiAndGetAToken:41->clientCredentialsToken:62 1 expectation failed.
Expected status code <200> but was <401>.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
The token endpoint doesn’t challenge, so challenged Basic never sent the client’s secret, and the endpoint answered 401. Notice the count, Tests run: 1: the failure is in @BeforeAll, so JUnit doesn’t run any of the five tests. The stack trace, startApiAndGetAToken:41->clientCredentialsToken:62, points at the helper, not at a test.
Put .preemptive() back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
401 with "error": "invalid_client" and no WWW-Authenticate | The client authenticated with challenged Basic, so the secret was never sent | Use auth().preemptive().basic(..) |
401 with "error": "invalid_client" and WWW-Authenticate: Basic realm="token" | The client id or secret is wrong | Check the client credentials |
400 with "error": "invalid_scope" | A scope the client may not have, or scopes separated by commas | Ask only for allowed scopes, separated by spaces |
Every test in the class fails with Tests run: 1 | Getting the token in @BeforeAll failed | Read the stack trace from the helper |
Try It Yourself
Exercise 1: Check a Payments Token’s Claims
Add a test called aPaymentsTokenCarriesBothScopes that gets a token for tpp-payments with client_secret_basic and the scopes accounts:read payments:write. Check the scope in the token response, then decode the token and check its client_id, its scope, that it lives exactly 300 seconds, and that its header’s alg is RS256.
Hint
Run the grant inline, as theTokenResponse does, and extract the access_token. The header is part [0] of the token, and the lifetime is exp minus iat; read both with getLong(..).
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
void aPaymentsTokenCarriesBothScopes() {
String token = bank()
.auth().preemptive().basic("tpp-payments", "payments-secret")
.formParam("grant_type", "client_credentials")
.formParam("scope", "accounts:read payments:write")
.when()
.post("/oauth2/token")
.then()
.statusCode(200)
.body("scope", equalTo("accounts:read payments:write"))
.extract().path("access_token");
String[] parts = token.split("\\.");
JsonPath header = JsonPath.from(new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8));
JsonPath claims = JsonPath.from(new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8));
assertEquals("tpp-payments", claims.getString("client_id"));
assertEquals("accounts:read payments:write", claims.getString("scope"));
assertEquals(300, claims.getLong("exp") - claims.getLong("iat"));
assertEquals("RS256", header.getString("alg"));
}
Exercise 2: Ask for a Scope the Client May Not Have
Add a test called aClientCantAskForMoreThanItMayHave that asks for the scope payments:write as tpp-accounts. Check that the token endpoint answers 400 with Cache-Control: no-store, the error invalid_scope, and an error_description that names the scope.
Hint
Start from theTokenResponse, and add the scope form parameter. Token errors use RFC 6749’s error and error_description fields, not RFC 9457 problems.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aClientCantAskForMoreThanItMayHave() {
bank()
.auth().preemptive().basic("tpp-accounts", "accounts-secret")
.formParam("grant_type", "client_credentials")
.formParam("scope", "payments:write")
.when()
.post("/oauth2/token")
.then()
.statusCode(400)
.header("Cache-Control", "no-store")
.body("error", equalTo("invalid_scope"))
.body("error_description", containsString("payments:write"));
}
Add import static org.hamcrest.Matchers.containsString; to the class.
Summary
You built BearerTokenTest, which gets an access token with the client credentials grant once per class, checks the token endpoint’s contract, authenticates the client in both ways, sends the token, and reads its claims. No token expires overnight in your tests any more, because each run gets its own.
- The client credentials grant gets a token with a form post of
grant_type=client_credentialsto the token endpoint. - The client authenticates with
client_secret_basic, sent preemptively, orclient_secret_post; several scopes are separated by spaces. - Check the token response’s contract, including
Cache-Control: no-store, and its errors, which follow RFC 6749. - Send the token with
auth().oauth2(..), which writesAuthorization: Bearer <token>, and get it once per class in@BeforeAll. - Decode a JWT’s claims to check what was issued, and leave validating the token to the server.
Here are the commands you used in this guide:
1
mvn test -pl module-07 -Dtest=BearerTokenTest
What’s Next
Next: continue with Write Negative Security Tests for OAuth 2.0 in REST Assured, which proves the API refuses missing, expired, forged and under-scoped tokens.
The code:
- The finished test class:
BearerTokenTest.java - The code and run commands for this module: Module 7 README
Go deeper:
- RFC 6749: The OAuth 2.0 Authorization Framework, for the client credentials grant and token errors.
- RFC 6750: Bearer Token Usage, for sending tokens.
- RFC 9068: JWT Profile for OAuth 2.0 Access Tokens, for the claims a JWT access token carries.
Related guides:
- Test HTTP Basic Authentication in REST Assured, for why the client authenticates preemptively.
- Read Many Values With JsonPath and XmlPath in REST Assured, for
JsonPath.from(..).
