Q9 of 40 · REST Assured

How do you handle authentication (basic auth, bearer token) in REST Assured?

REST AssuredJuniorrest-assuredauthenticationbasic-authbearer-tokenfundamentals

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());

// WHAT INTERVIEWERS LOOK FOR

Correct method names for basic and bearer auth, and the important distinction between non-preemptive and preemptive basic auth. Knowing to centralise auth in RequestSpecBuilder is a mid-level signal in a junior question.

// COMMON PITFALL

Using non-preemptive basic auth against APIs that don't issue a 401 challenge — the request will fail or return 401 because REST Assured waits for a challenge that never arrives.