← Back to libraryQuestion 239 of 468
🔌REST AssuredIntermediate

Authentication (Basic, Bearer, OAuth2)

📌 Definition:

REST Assured supports authentication via .auth() (basic, digest, preemptive) and by setting an Authorization header for token/OAuth2 flows. Choosing the right mechanism matches the API's security scheme.

📖 Detailed Explanation:

given().auth().basic('user', 'pass') sends Basic auth; .auth().preemptive().basic(...) sends credentials on the first request without waiting for a 401 challenge (often required). For token-based APIs, add the header: .header('Authorization', 'Bearer ' + token), where the token is typically obtained from a prior login/extract. .auth().oauth2(token) is a shortcut for Bearer. There's also digest and form auth. A common pattern is to fetch a token once (in setup) and attach it to subsequent requests, or bake it into a RequestSpecification. Getting preemptive vs challenge-based basic auth right is a frequent gotcha.

🔑 Key Points:
  • auth().basic()/preemptive().basic() for Basic auth
  • Bearer/OAuth2: header('Authorization','Bearer '+token) or auth().oauth2(token)
  • Fetch token once, reuse across requests (or in a spec)
  • preemptive() sends creds upfront (avoids 401 challenge)
🌍 Real-World Example:

Token flow: String token = given().body(creds).post('/auth/login').then().extract().path('access_token'); then reuse given().auth().oauth2(token).get('/secure')... for every protected call.

🎯 Scenario-Based Interview Question:

Basic-auth tests fail with 401 even though credentials are correct. What subtle configuration usually fixes it?