Q9 of 40 · REST Assured
How do you handle authentication (basic auth, bearer token) in REST Assured?
Short answer
Short answer: For basic auth use .auth().preemptive().basic(user, pass) — preemptive skips the 401 challenge round-trip. For bearer tokens use .header("Authorization", "Bearer " + token) or .auth().oauth2(token) in 5.x. Centralise auth in RequestSpecBuilder so every test inherits it without repetition.
Detail
REST Assured has a dedicated .auth() sub-spec for common patterns:
Basic auth: .auth().basic(user, pass) waits for a 401 challenge before sending credentials. .auth().preemptive().basic(user, pass) sends the Authorization: Basic ... header upfront — always use preemptive unless the server explicitly requires challenge-response.
Bearer / OAuth 2.0: REST Assured 5.x adds .auth().oauth2(accessToken) which sets Authorization: Bearer <token>. In earlier versions, use .header("Authorization", "Bearer " + token) directly.
In RequestSpecBuilder: centralise auth once so all tests inherit it:
new RequestSpecBuilder()
.setAuth(preemptive().basic(user, pass))
.build()
Getting the access token itself (client credentials flow, PKCE) is a separate concern covered in the senior OAuth 2.0 question.
// EXAMPLE
// Basic auth — preemptive (no 401 round-trip)
given()
.auth().preemptive().basic("admin", "secret")
.baseUri("https://api.example.com")
.when()
.get("/admin/users")
.then()
.statusCode(200);
// Bearer token
given()
.header("Authorization", "Bearer " + accessToken)
// or in REST Assured 5.x: .auth().oauth2(accessToken)
.baseUri("https://api.example.com")
.when()
.get("/me")
.then()
.statusCode(200)
.body("email", notNullValue());