Skip to main content

Command Palette

Search for a command to run...

Authentication in RestAssured

Published
β€’5 min readβ€’View as Markdown

authentication is a core part of API testing in RestAssured, and mastering it is must-have for automation testers.

Let’s go step-by-step β€” covering all authentication types, their usage, code examples, when to use, and common errors.


πŸ” Authentication in RestAssured β€” Complete Guide

Authentication means verifying the identity of the API client (you or your test).
Most APIs require authentication to ensure only authorized users can access data.


🧩 1️⃣ No Authentication (Open API)

πŸ‘‰ Description

  • Public APIs that don’t require credentials.

  • Example: Open weather APIs, currency converters.

βœ… Example

given()
    .when()
    .get("https://api.zippopotam.us/us/90210")
.then()
    .statusCode(200)
    .log().all();

πŸ’‘ When to use

  • Open/public data endpoints

  • Simple testing or health check APIs


🧩 2️⃣ Basic Authentication

πŸ‘‰ Description

  • The simplest authentication type.

  • Sends username and password in the header (Base64 encoded).

⚠️ Not secure if used over HTTP (always use HTTPS).

βœ… Syntax

given()
    .auth()
    .basic("username", "password")
.when()
    .get("https://api.example.com/users")
.then()
    .statusCode(200);

βœ… Alternate Way (Preemptive)

given()
    .auth()
    .preemptive()
    .basic("username", "password")
.when()
    .get("https://api.example.com/users")
.then()
    .statusCode(200);

πŸ’‘ Difference:

TypeDescription
basic()Server first sends 401, then client sends credentials
preemptive().basic()Client sends credentials in the first request itself (faster)

🧩 3️⃣ Digest Authentication

πŸ‘‰ Description

  • More secure version of Basic Authentication.

  • Uses a hash of the password instead of sending it in plain text.

  • Common in legacy enterprise systems.

βœ… Example

given()
    .auth()
    .digest("username", "password")
.when()
    .get("https://api.example.com/secure/data")
.then()
    .statusCode(200);

πŸ’‘ When to use

  • APIs supporting Digest Authentication (older web servers or internal APIs)

🧩 4️⃣ Bearer Token / OAuth2 Token

πŸ‘‰ Description

  • The most common modern authentication.

  • Token is issued after login and sent with every request.

  • Used in most REST APIs (JWT, OAuth2, API keys).

βœ… Example

given()
    .auth()
    .oauth2("your_token_here")
.when()
    .get("https://api.github.com/user")
.then()
    .statusCode(200);

Or with Header manually:

given()
    .header("Authorization", "Bearer your_token_here")
.when()
    .get("https://api.github.com/user")
.then()
    .statusCode(200);

πŸ’‘ When to use

  • APIs using JWT, OAuth2, or token-based sessions (GitHub, Google, Jira, etc.)

🧩 5️⃣ API Key Authentication

πŸ‘‰ Description

  • Common for public APIs where a single key identifies the client.

  • Key is sent as a query param or header.

βœ… Example (Header)

given()
    .header("x-api-key", "12345abcde")
.when()
    .get("https://api.weatherapi.com/v1/current.json?q=London")
.then()
    .statusCode(200);

βœ… Example (Query Param)

given()
    .queryParam("appid", "your_api_key")
    .queryParam("q", "London")
.when()
    .get("https://api.openweathermap.org/data/2.5/weather")
.then()
    .statusCode(200);

πŸ’‘ When to use

  • External or third-party APIs (Google Maps, OpenWeather, NewsAPI, etc.)

🧩 6️⃣ Form Authentication

πŸ‘‰ Description

  • Used when the application authenticates using a login form (HTML form submission).

  • RestAssured can simulate form-based login.

βœ… Example

given()
    .auth()
    .form("username", "password", new FormAuthConfig("/login", "uname", "pwd"))
.when()
    .get("https://app.example.com/home")
.then()
    .statusCode(200);

πŸ’‘ Parameters:

ArgumentDescription
/loginLogin endpoint
unameUsername field name
pwdPassword field name

🧩 7️⃣ OAuth 1.0

πŸ‘‰ Description

  • Older version of OAuth (used by Twitter API v1).

  • Uses consumer key, secret, token, and token secret.

βœ… Example

given()
    .auth()
    .oauth("consumerKey", "consumerSecret", "accessToken", "secretToken")
.when()
    .get("https://api.twitter.com/1.1/statuses/home_timeline.json")
.then()
    .statusCode(200);

πŸ’‘ When to use

  • Only when working with legacy APIs (Twitter API v1.1, some banking APIs)

🧩 8️⃣ OAuth 2.0 (Access Token Flow)

πŸ‘‰ Description

  • The modern standard for authentication (used by Google, GitHub, Azure, etc.)

  • Involves:

    1. Getting access token using client credentials.

    2. Using token in further requests.

βœ… Step 1: Get Token

Response tokenResponse = given()
    .formParam("client_id", "myClientId")
    .formParam("client_secret", "mySecret")
    .formParam("grant_type", "client_credentials")
.when()
    .post("https://authserver.com/oauth/token");

String accessToken = tokenResponse.jsonPath().getString("access_token");

βœ… Step 2: Use Token

given()
    .header("Authorization", "Bearer " + accessToken)
.when()
    .get("https://api.example.com/resource")
.then()
    .statusCode(200);

πŸ‘‰ Description

  • Used in traditional web apps.

  • You first log in β†’ receive a session cookie β†’ use it for later requests.

βœ… Example

Response res = given()
    .formParam("username", "admin")
    .formParam("password", "admin123")
.when()
    .post("https://app.example.com/login");

String sessionId = res.getCookie("JSESSIONID");

given()
    .cookie("JSESSIONID", sessionId)
.when()
    .get("https://app.example.com/dashboard")
.then()
    .statusCode(200);

🧠 10️⃣ Summary Table

TypeSecurity LevelUse CaseExample
No Auth❌Open/Public APIsPublic weather APIs
Basic⚠️ LowLegacy systemsInternal APIs
Digestβœ… MediumEnterpriseInternal/secure APIs
Bearer/OAuth2πŸ”’ HighModern APIsGitHub, Google, Jira
API Keyβœ… MediumThird-partyOpenWeather, NewsAPI
Form Auth⚠️ LowWeb appsLogin forms
OAuth1.0βœ… MediumLegacy OAuthTwitter v1
Session/Cookie⚠️ MediumWeb portalsOld-style logins

βš™οΈ 11️⃣ Best Practices

βœ… Always use HTTPS (never send credentials over HTTP)
βœ… Use Config/Properties file for credentials, not hardcoded values
βœ… Use token refresh logic for long-running tests
βœ… Parameterize auth tokens for CI/CD (Jenkins secrets or environment variables)
βœ… Add utility methods for token retrieval and reuse