Introduction
Playwright API Authentication Testing is one of the most important skills for QA automation engineers working with REST APIs. Most modern applications protect their APIs using authentication methods such as Basic Authentication, Bearer Tokens, API Keys, OAuth 2.0, or JWT (JSON Web Token). Before validating business functionality, automation tests must first authenticate successfully.
Playwright provides a powerful built-in API testing capability that makes it easy to authenticate, send secure HTTP requests, validate responses, and integrate API testing with UI automation. If you are a Selenium engineer transitioning to Playwright, an API tester, or preparing for automation interviews, this tutorial will help you learn how to perform API authentication testing in Playwright using TypeScript.
What is API Authentication Testing?
API Authentication Testing verifies that an API correctly authenticates users or applications before allowing access to protected resources.
Authentication ensures that only authorized users can access secured endpoints.
Without authentication, sensitive information such as customer data, banking transactions, and healthcare records would be exposed.
Why Authentication Testing Matters
- Protects sensitive data
- Prevents unauthorized access
- Verifies security implementation
- Ensures API reliability
- Validates access control
- Supports compliance requirements
Why Use Playwright for API Authentication Testing?
Playwright includes built-in support for REST API testing, eliminating the need for additional HTTP libraries in many scenarios.
Benefits
- Built-in API request support
- TypeScript integration
- Fast execution
- Simple assertions
- Authentication header support
- Request and response validation
- Parallel execution
- CI/CD integration
- UI and API testing in one framework
These features make Playwright API Automation an excellent choice for enterprise projects.
Types of API Authentication
The most common authentication mechanisms used in REST APIs are shown below.
| Authentication Type | Description | Common Usage |
| Basic Authentication | Username and password encoded in Base64 | Internal APIs |
| Bearer Token | Access token in Authorization header | REST APIs |
| API Key | Unique application key | Public APIs |
| OAuth 2.0 | Authorization framework | Google, Microsoft APIs |
| JWT | JSON Web Token | Modern web applications |
Understanding these methods is essential for Playwright REST API Testing.
Setting Up Playwright for API Testing
Step 1: Create a Playwright Project
mkdir PlaywrightAPITesting
cd PlaywrightAPITesting
npm init playwright@latest
Select:
- TypeScript
- Playwright Test
- Install browsers
Step 2: Project Structure
PlaywrightAPITesting
│
├── api
│ AuthAPI.ts
│ UserAPI.ts
│
├── tests
│ auth.spec.ts
│
├── utils
│ TokenManager.ts
│
├── config
│ environment.ts
│
├── .env
│
└── playwright.config.ts
This folder structure keeps authentication logic separate from test scripts.
Implementing Authentication Examples in TypeScript
1. Basic Authentication Example
import { test, expect } from ‘@playwright/test’;
test(‘Basic Authentication’, async ({ request }) => {
const response = await request.get(
‘https://api.example.com/users’,
{
headers: {
Authorization:
‘Basic ‘ +
Buffer.from(‘admin:password123’).toString(‘base64’)
}
}
);
expect(response.status()).toBe(200);
});
Explanation
- Username and password are encoded using Base64.
- The value is sent in the Authorization header.
- A status code of 200 confirms successful authentication.
2. Bearer Token Authentication
Bearer Token Authentication is one of the most common methods used in modern REST APIs.
import { test, expect } from ‘@playwright/test’;
test(‘Bearer Token Authentication’, async ({ request }) => {
const token = “your_access_token”;
const response = await request.get(
‘https://api.example.com/profile’,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
expect(response.ok()).toBeTruthy();
});
Explanation
- The token is stored in a variable.
- The Authorization header starts with Bearer.
- response.ok() validates that the request completed successfully.
3. API Key Authentication
Many third-party APIs use API keys instead of tokens.
const response = await request.get(
‘https://api.example.com/products’,
{
headers: {
“x-api-key”: “123456789”
}
}
);
Explanation
- The API key is sent in a custom request header.
- The server validates the key before processing the request.
4. OAuth 2.0 Authentication
OAuth 2.0 usually requires obtaining an access token first.
const tokenResponse = await request.post(
‘https://api.example.com/oauth/token’,
{
form: {
client_id: ‘client123’,
client_secret: ‘secret123’,
grant_type: ‘client_credentials’
}
}
);
const token = (await tokenResponse.json()).access_token;
Explanation
- A POST request retrieves the access token.
- Client credentials are sent in the request body.
- The returned token is stored for later API calls.
5. JWT Authentication Example
Many enterprise applications use JWT.
const response = await request.get(
‘https://api.example.com/orders’,
{
headers: {
Authorization: `Bearer ${jwtToken}`
}
}
);
JWT tokens are treated similarly to Bearer tokens but contain encoded user information.
Sending Authenticated API Requests
After authentication, requests can access protected resources.
const response = await request.get(
‘https://api.example.com/customers’,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
This approach is commonly used for:
- Customer APIs
- Banking APIs
- Healthcare APIs
- E-commerce APIs
Validating API Responses and Status Codes
Authentication testing should validate more than just the status code.
const body = await response.json();
expect(response.status()).toBe(200);
expect(body.success).toBe(true);
expect(body.user.id).toBeDefined();
Verify
- Status code
- Response body
- Authentication success
- Required fields
- Error messages (negative scenarios)
Managing Tokens and Environment Variables
Avoid hardcoding sensitive credentials.
Example .env file:
API_URL=https://api.example.com
TOKEN=eyJhbGc…
CLIENT_SECRET=secret123
Access values using environment variables.
const token = process.env.TOKEN;
Benefits
- Improved security
- Easy environment switching
- Cleaner code
- Better CI/CD integration
Enterprise API Authentication Framework Structure
PlaywrightAPIFramework
│
├── api
│ LoginAPI.ts
│ UserAPI.ts
│
├── auth
│ TokenManager.ts
│
├── tests
│ login.spec.ts
│
├── fixtures
│ apiFixture.ts
│
├── config
│ environment.ts
│
├── utils
│ Logger.ts
│
└── .env
Folder Explanation
| Folder | Purpose |
| api | API service classes |
| auth | Token management |
| tests | Test scripts |
| fixtures | Shared setup |
| config | Environment configuration |
| utils | Logging and helper methods |
This structure is commonly used in enterprise Playwright API Automation frameworks.
Best Practices
Follow these best practices for Playwright API Authentication Testing:
- Store tokens in environment variables.
- Refresh expired tokens automatically.
- Separate authentication logic from tests.
- Validate both status codes and response bodies.
- Reuse authentication methods.
- Avoid hardcoded credentials.
- Log request and response details.
- Test positive and negative authentication scenarios.
- Protect secrets in CI/CD pipelines.
- Rotate API keys regularly.
- Use HTTPS for secure communication.
- Generate API test reports.
Common Mistakes
Avoid these common mistakes:
- Hardcoding access tokens.
- Ignoring token expiration.
- Validating only status codes.
- Sharing credentials in source code.
- Not testing unauthorized access.
- Repeating authentication logic.
- Ignoring response body validation.
- Forgetting to secure environment files.
Real-Time API Authentication Scenarios
Scenario 1: Banking Application
Login API
│
▼
Generate Token
│
▼
Account API
│
▼
Transfer API
│
▼
Transaction History
Scenario 2: E-Commerce Application
- Login
- Receive JWT token
- Search products
- Add to cart
- Checkout
- Logout
Scenario 3: Healthcare Portal
- Authenticate doctor
- Retrieve patient records
- Update prescriptions
- Validate authorization rules
Playwright API Authentication Interview Questions
1. What is API authentication?
The process of verifying the identity of a user or application before granting API access.
2. Why is API authentication important?
It protects secured resources from unauthorized access.
3. Which authentication methods does Playwright support?
Basic Authentication, Bearer Token, API Key, OAuth 2.0, JWT, and custom headers.
4. What is Bearer Token Authentication?
A token-based authentication method that sends an access token in the Authorization header.
5. What is Basic Authentication?
A method that sends a Base64-encoded username and password.
6. What is JWT?
A JSON Web Token used for secure authentication and authorization.
7. What is OAuth 2.0?
An authorization framework that allows secure delegated access.
8. Why should tokens be stored in environment variables?
To improve security and avoid exposing secrets in source code.
9. How do you validate authentication?
By checking the status code, response body, and authorization behavior.
10. Can Playwright combine API and UI testing?
Yes. API calls can create test data before executing UI automation.
FAQs
Is Playwright good for API authentication testing?
Yes. It provides built-in support for authenticated REST API requests and integrates well with UI automation.
Can Playwright test OAuth APIs?
Yes. You can retrieve OAuth access tokens and use them in authenticated requests.
Does Playwright support JWT authentication?
Yes. JWT tokens are passed using the Authorization: Bearer header.
Should API credentials be hardcoded?
No. Store credentials in environment variables or secure secret managers.
Can Playwright test unauthorized access?
Yes. Negative test cases should verify 401 Unauthorized and 403 Forbidden responses.
Can Playwright integrate with CI/CD?
Yes. It works with GitHub Actions, Jenkins, Azure DevOps, GitLab CI, and other CI/CD platforms.
Is Playwright suitable for beginners?
Yes. Its built-in API features and TypeScript support make it beginner-friendly.
Can authentication logic be reused?
Yes. Create reusable authentication service classes and token managers.
