Types of Authentication

Authentication is the process of verifying the identity of the client making an API request.

Before accessing secured APIs, the server verifies whether the client is authorized to access the requested resource.

In API automation, the most commonly used authentication mechanisms are:


Advertisement

Interview Answer

"Authentication verifies who is making the API request. In API automation, I have worked with Basic Authentication, Bearer Token (JWT), API Key Authentication, and OAuth 2.0. In real-world projects, we primarily use Bearer Token authentication, where a login API generates a JWT token that is passed in the Authorization header for all secured API requests."


Types of Authentication

Authentication Type Based On Purpose Common Tools Automatable
Basic Authentication Username & Password Simple authentication REST Assured, Postman ✔
Bearer Token / JWT Token Secure authentication REST Assured ✔
API Key API Key Controlled API access REST Assured, Postman ✔
OAuth 2.0 Access Token Third-party integrations REST Assured ✔

Authentication Overview

Client
   │
   ▼
Authentication
   │
   ├── Basic Auth
   ├── Bearer Token
   ├── API Key
   └── OAuth 2.0
   │
   ▼
Server

Why Token-Based Authentication?

Modern applications prefer Bearer Token (JWT) authentication because:

  • Passwords are not sent with every request.
  • Tokens have limited validity.
  • More secure than Basic Authentication.
  • Easy to scale.
  • Widely used in REST APIs.

When Is OAuth Used?

OAuth 2.0 is commonly used for:

  • Google Login
  • Facebook Login
  • Microsoft Login
  • GitHub Login
  • Third-party integrations

Basic Authentication

Basic Authentication is one of the simplest authentication mechanisms.

The client sends:

  • Username
  • Password

with every API request.

The server validates the credentials before processing the request.


Basic Authentication Flow

Client
   │
Username + Password
   │
   ▼
Server
   │
Validate Credentials
   │
   ▼
Response

REST Assured Example

given()
        .auth()
        .basic("admin", "admin123")

.when()
        .get("/users")

.then()
        .statusCode(200);

Preemptive Basic Authentication

REST Assured also supports Preemptive Basic Authentication, where credentials are sent immediately without waiting for the server's authentication challenge.

given()
        .auth()
        .preemptive()
        .basic("admin", "admin123")

.when()
        .get("/users");

Advantages

  • Simple implementation
  • Easy to automate
  • Suitable for internal APIs
  • Supported by almost all HTTP clients

Limitations

  • Username and password are sent with every request.
  • Less secure than token-based authentication.
  • Should always be used over HTTPS.

Interview Answer

"Basic Authentication sends the username and password with every API request. In REST Assured, I use .auth().basic() or .auth().preemptive().basic() to authenticate secured endpoints."


Bearer Token / JWT Authentication

Bearer Token authentication is the most commonly used authentication mechanism in REST APIs.

Instead of sending the username and password with every request, the client:

  1. Logs in once.
  2. Receives a JWT token.
  3. Uses that token for subsequent API requests.

JWT Authentication Flow

Login API
    │
    ▼
Generate JWT Token
    │
    ▼
Store Token
    │
    ▼
Authorization Header
    │
    ▼
Secured APIs

Real-Time Workflow

Login API
     │
     ▼
Extract Token
     │
     ▼
Store Token
     │
     ▼
GET API
POST API
PUT API
DELETE API

Interview Answer

"In our automation framework, we authenticate using a Login API that returns a JWT token. We extract the token, store it globally, and reuse it in the Authorization header for secured APIs such as Create User, Update User, Get User, and Delete User."


Passing a Token in REST Assured

After authentication, the generated token must be passed with every secured request.

The standard header format is:

Authorization: Bearer <token>

Step 1: Generate Token

String token =

given()
        .contentType(ContentType.JSON)
        .body(loginPayload)

.when()
        .post("/login")

.then()
        .statusCode(200)
        .extract()
        .path("token");

Step 2: Pass Token

given()
        .header("Authorization", "Bearer " + token)
        .contentType(ContentType.JSON)

.when()
        .get("/users")

.then()
        .statusCode(200);

Complete Flow

Login API
     │
     ▼
Extract Token
     │
     ▼
Store Token
     │
     ▼
Authorization Header
     │
     ▼
Secured APIs

Reusing the Token

Instead of generating a token before every test, frameworks usually generate it once.

Example:

public class UserApiTest {
    private RequestSpecification authSpec;

    @BeforeClass
    public void generateToken() {
        RestAssured.baseURI = ConfigReader.get("apiBaseUrl");

        String token = given()
                .contentType(ContentType.JSON)
                .body(Map.of("username", "admin", "password", System.getenv("API_PASSWORD")))
            .when()
                .post("/login")
            .then()
                .statusCode(200)
                .extract().path("token");

        authSpec = new RequestSpecBuilder()               // reusable: base URI, JSON, auth header
                .setContentType(ContentType.JSON)
                .addHeader("Authorization", "Bearer " + token)
                .build();
    }

    @Test
    public void getUsers() {
        given().spec(authSpec)
        .when().get("/users")
        .then().statusCode(200);
    }

    @Test
    public void getUsersWithoutToken() {
        given().when().get("/users")
        .then().statusCode(401);                          // negative test: no token
    }
}

A RequestSpecification keeps the auth header in one place, so every test gets it with .spec(authSpec) — and the negative test simply leaves it out. Read the password from an environment variable, never from code. If tokens expire during a long suite, wrap token creation in a small utility that refreshes the token when it's close to expiry.

All test cases use the same token until it expires.


Advantages

  • More secure
  • Better scalability
  • Faster execution
  • Reduced authentication overhead
  • Password not sent repeatedly

Real-Time Example

In my project, we generated the JWT token once inside a @BeforeClass method and reused it across multiple secured APIs, including Create User, Update User, Delete User, and Get User. A new token was generated only after expiry or logout.


API Key Authentication

API Key authentication grants access using a unique key issued by the API provider.

The key is commonly sent:

  • In the request header
  • As a query parameter

Header Example

x-api-key: ABC123XYZ

REST Assured Example

given()
        .header("x-api-key", "ABC123XYZ")

.when()
        .get("/products")

.then()
        .statusCode(200);

Advantages

  • Simple implementation
  • Easy automation
  • Common for public APIs
  • Good for service-to-service communication

OAuth 2.0

OAuth 2.0 is an authorization framework that enables secure third-party access without sharing user passwords.

Instead of giving your password to another application, you grant it temporary access using an Access Token.


OAuth Flow (Client Credentials Grant)

Client
   │
Client ID + Client Secret
   │
   ▼
Authorization Server
   │
Generate Access Token
   │
   ▼
Client
   │
Authorization: Bearer Token
   │
   ▼
Protected API

Real-Time Examples

OAuth is commonly used for:

  • Login with Google
  • Login with Facebook
  • Login with Microsoft
  • Login with GitHub

REST Assured Example

given()
        .auth()
        .oauth2(accessToken)

.when()
        .get("/profile")

.then()
        .statusCode(200);

Interview Answer

"OAuth 2.0 is an authorization framework that allows secure third-party access using access tokens instead of passwords. In REST Assured, I use .auth().oauth2(accessToken) to authenticate OAuth-protected APIs."


Authentication Status Codes

Authentication testing includes validating the appropriate HTTP status code for each scenario.

Scenario Expected Status Code
Valid Token 200 OK
Invalid Token 401 Unauthorized
Missing Token 401 Unauthorized
Expired Token 401 Unauthorized
Invalid Credentials 401 Unauthorized
Insufficient Permissions 403 Forbidden

Authentication Validation Flow

Request
   │
   ▼
Authentication
   │
   ├── Valid Token
   │       │
   │       ▼
   │     200 OK
   │
   ├── Missing Token
   │       │
   │       ▼
   │   401 Unauthorized
   │
   ├── Invalid Token
   │       │
   │       ▼
   │   401 Unauthorized
   │
   └── Expired Token
           │
           ▼
      401 Unauthorized

Why expired is 401, not 403: an expired token means the client is no longer authenticated — logging in again fixes it — so the standard response is 401 Unauthorized, often with a WWW-Authenticate: Bearer error="invalid_token" header. 403 Forbidden means the client is authenticated but lacks permission (a normal user calling an admin endpoint). Some APIs return 403 for expired tokens anyway — assert what your API specifies, and raise it with the developers if it contradicts the standard.


Token Expiry Testing

Typical authentication test cases include:

  • Valid token
  • Invalid token
  • Missing token
  • Expired token
  • Revoked token
  • Logout token
  • Unauthorized user

Best Practices

  • Generate tokens dynamically instead of hardcoding them.
  • Store tokens securely.
  • Generate the token once and reuse it until expiry.
  • Validate authentication status codes.
  • Test expired and invalid token scenarios.
  • Never expose credentials or tokens in logs.
  • Use HTTPS for all authenticated APIs.

📚 Official documentation: REST Assured official site · MDN: HTTP

Frequently Asked Questions (FAQs)

1. What types of authentication have you worked on?

I have worked with:

  • Basic Authentication
  • Bearer Token (JWT) Authentication
  • API Key Authentication
  • OAuth 2.0

In real-world projects, Bearer Token authentication is the most commonly used approach for securing REST APIs.


2. What is Basic Authentication?

Basic Authentication sends the username and password with every API request. REST Assured supports it using:

.auth().basic(username, password)

or

.auth().preemptive().basic(username, password)

3. How do you pass a token in REST Assured?

After generating the token from the Login API, pass it in the Authorization header:

.header("Authorization", "Bearer " + token)

This authenticates subsequent secured API requests.


4. How do you generate and reuse a token?

I call the Login API, extract the token using:

.extract().path("token")

or

response.jsonPath().getString("token")

Then I store the token (typically in a @BeforeClass setup method or a shared utility) and reuse it across multiple secured API requests until it expires.


5. What is OAuth 2.0?

OAuth 2.0 is an authorization framework that enables secure third-party integrations using access tokens instead of sharing user passwords. REST Assured supports OAuth authentication using:

.auth().oauth2(accessToken)

6. What status codes do you expect for authentication scenarios?

Typical authentication status codes are:

  • 200 OK → Valid token
  • 401 Unauthorized → Invalid, missing or expired token (not authenticated)
  • 403 Forbidden → Authenticated but without permission

These scenarios are important negative test cases in API automation frameworks.


Authentication vs Authorization

Authentication answers "who are you?" (login, token, API key) — failure is 401. Authorization answers "what may you do?" (roles, permissions, owning the record) — failure is 403. Test both: a valid token for user A must not read or change user B's data (change the ID in the URL — a very common real vulnerability). More: API Authentication: OAuth & JWT and API Security Testing.

See the token travel from the login response into the next request's header in the REST Assured Visualizer.

From Real Projects

I've tested APIs at the level of CRUD operations, HTTP methods and JSON path validation, and written automation in Java with TestNG. REST Assured brings those together in one Java library — which is why testers with Selenium and TestNG experience usually pick it up quickly. Start with one resource and automate its full CRUD cycle. Testsigma supports web, mobile and API test automation, so understanding APIs was part of understanding the product I was testing. Keep credentials in environment variables or a secrets store, never in code.