OWASP ZAP Authentication Techniques
Advanced authentication handling in OWASP ZAP for testing secure applications
Authentication is a critical aspect of web application security testing. OWASP ZAP provides robust support for testing authenticated applications using various authentication mechanisms. This guide covers advanced authentication techniques to help you effectively test secure applications.
Authentication Overview
When testing web applications, you often need to:
- Authenticate to access protected functionality
- Maintain authenticated sessions during testing
- Test different user roles and permissions
- Verify authentication security controls
ZAP provides several methods to handle these requirements:
Authentication Methods
ZAP supports multiple authentication methods:
- Manual Authentication: Manually log in through the browser
- Form-based Authentication: Standard username/password forms
- HTTP/NTLM Authentication: Basic, Digest, NTLM authentication
- JSON-based Authentication: REST API authentication
- Script-based Authentication: Custom authentication flows
Each method is configured at the context level, allowing different authentication mechanisms for different applications or parts of an application.
Setting Up Authentication
Context Configuration
Create a Context
- Right-click on a site in the Sites tree
- Select Include in Context > New Context
- Enter a name for the context
- Define the scope using include/exclude patterns
Configure Authentication Method
- In the context dialog, select Authentication
- Choose the appropriate authentication method
- Configure method-specific settings (covered in detail below)
Configure Session Management
- In the context dialog, select Session Management
- Choose the appropriate session management method
- Configure method-specific settings
Create Users
- In the context dialog, select Users
- Click Add to create a new user
- Enter a name for the user
- Configure authentication credentials
- Enable the user for testing
Authentication Methods in Detail
Form-Based Authentication
Form-based authentication is the most common method used by web applications.
Configure Form-Based Authentication
- In the context authentication panel, select Form-based Authentication
- Configure the following settings:
- Login URL: The URL of the login page (e.g.,
https://example.com/login
) - Login Request POST Data: The form parameters (e.g.,
username=%username%&password=%password%
) - Username Parameter: Parameter name for username (e.g.,
username
) - Password Parameter: Parameter name for password (e.g.,
password
)
- Login URL: The URL of the login page (e.g.,
Configure Authentication Verification
- Set up logged-in/out indicators:
- Logged In Indicator: Regex pattern that appears when logged in (e.g.,
Logout|Welcome
) - Logged Out Indicator: Regex pattern that appears when logged out (e.g.,
Login|Sign in
)
- Logged In Indicator: Regex pattern that appears when logged in (e.g.,
These patterns help ZAP determine if the authentication was successful and if the session is still valid.
Create Users
- In the context Users panel, add users with their credentials
- For each user, provide:
- Username: The username to use
- Password: The password to use
- Enable the users for testing
Note:
The login request POST data must use {%username%}
and {%password%}
as placeholders. ZAP will replace these with the actual credentials when authenticating.
HTTP Authentication
HTTP authentication is used by applications that rely on HTTP Basic, Digest, or NTLM authentication.
Configure HTTP Authentication
- In the context authentication panel, select HTTP/NTLM Authentication
- Configure the following settings:
- Hostname: The hostname requiring authentication
- Port: The port number (usually 80 or 443)
- Realm: The authentication realm (if known)
- Authentication Type: Basic, Digest, or NTLM
Create Users
- In the context Users panel, add users with their credentials
- For each user, provide:
- Username: The username to use
- Password: The password to use
- Enable the users for testing
JSON-Based Authentication
Many modern applications, especially single-page applications (SPAs) and APIs, use JSON for authentication.
Configure JSON-Based Authentication
- In the context authentication panel, select JSON-based Authentication
- Configure the following settings:
- Login URL: The authentication endpoint (e.g.,
https://example.com/api/login
) - Login Request POST Data: JSON payload (e.g.,
{"username":"{%username%}","password":"{%password%}"}
) - Username Parameter: JSON path to username (e.g.,
username
) - Password Parameter: JSON path to password (e.g.,
password
)
- Login URL: The authentication endpoint (e.g.,
Configure Token Extraction
For applications that return authentication tokens:
- Set the Token URL: URL that returns the token (usually same as login URL)
- Set the Token Element: JSON path to the token (e.g.,
$.token
or$.data.access_token
) - Configure how the token should be used:
- HTTP Header: Add token to requests as a header (e.g.,
Authorization: Bearer {%token%}
) - Cookie: Add token as a cookie
- HTTP Header: Add token to requests as a header (e.g.,
Configure Authentication Verification
Set up logged-in/out indicators as described in form-based authentication
Note:
For complex JSON structures, you may need to use JSONPath expressions to extract tokens. For example, $.data.auth.token
for a token nested in a data object.
Script-Based Authentication
Script-based authentication provides the most flexibility for complex authentication flows.
Create Authentication Script
- Go to Tools > Scripts
- Select the Authentication script type
- Click New to create a new script
- Select the scripting language (JavaScript, Python, etc.)
- Implement the required functions:
authenticate(helper, paramsValues, credentials)
: Performs the authenticationgetRequiredParamsNames()
: Returns parameters needed by the scriptgetCredentialsParamsNames()
: Returns credential parametersisAuthenticated(helper, paramsValues, credentials)
: Checks if authenticated
Configure Script-Based Authentication
- In the context authentication panel, select Script-Based Authentication
- Select your authentication script
- Configure script parameters as required
Create Users
Create users with credentials as required by your script
Example Authentication Script
Here's an example of a JavaScript authentication script for a token-based API:
// Authentication script for token-based API
// Define required parameters
function getRequiredParamsNames() {
return ["loginUrl", "tokenPath"];
}
// Define credential parameters
function getCredentialsParamsNames() {
return ["username", "password"];
}
// Authenticate function
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("loginUrl");
var tokenPath = paramsValues.get("tokenPath");
var username = credentials.get("username");
var password = credentials.get("password");
// Prepare the login request
var requestBody = '{"username":"' + encodeURIComponent(username) +
'","password":"' + encodeURIComponent(password) + '"}';
// Set up the authentication request details
var method = "POST";
var headers = "Content-Type: application/json\r\n";
var body = requestBody;
// Send the authentication request
var response = helper.prepareMessage();
response = helper.sendAndReceive(loginUrl, method, headers, body, response);
// Extract the authentication token
var responseBody = response.getResponseBody().toString();
var json = JSON.parse(responseBody);
// Use JSONPath to extract the token
var token = extractValue(json, tokenPath);
if (token) {
// Add the token as a header for future requests
helper.getHttpSender().addHeader("Authorization", "Bearer " + token);
return true;
}
return false;
}
// Check if the user is authenticated
function isAuthenticated(helper, paramsValues, credentials) {
// This is a simple example - you might need to check a protected resource
var requestHeader = helper.getHttpMessage().getRequestHeader();
return requestHeader.getHeader("Authorization") != null;
}
// Helper function to extract values using JSONPath-like syntax
function extractValue(json, path) {
var parts = path.split('.');
var current = json;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part.startsWith('$')) {
continue; // Skip the root indicator
}
if (current[part] === undefined) {
return null;
}
current = current[part];
}
return current;
}
Session Management
Session management works alongside authentication to maintain the authenticated state during testing.
Using Authenticated Scanning
Once authentication is configured, you can perform authenticated scanning.
Enable Forced User Mode
- Select a user in the Users panel
- Click Set as Forced User
- Enable forced user mode by clicking the "person" icon in the toolbar
- ZAP will now authenticate as this user for all requests
Spider with Authentication
- Right-click on a target in the Sites tree
- Select Attack > Spider
- In the Spider dialog:
- Select the appropriate context
- Select the user to authenticate as
- Configure other spider options
- Click Start Scan
Active Scan with Authentication
- Right-click on a target in the Sites tree
- Select Attack > Active Scan
- In the Active Scan dialog:
- Select the appropriate context
- Select the user to authenticate as
- Configure other scan options
- Click Start Scan
Advanced Authentication Scenarios
Multi-Factor Authentication (MFA)
Testing applications with MFA requires special handling:
Script-Based Approach
For applications with MFA:
- Create a script-based authentication script
- Implement the authentication flow:
- First factor (username/password)
- Handle second factor (if possible)
Options for handling the second factor:
- Use pre-generated backup codes
- Use a fixed TOTP seed and generate codes
- Implement a custom solution for your specific MFA
Manual Authentication with Session Import
If automated MFA handling is not possible:
- Manually authenticate through the browser
- Export the authenticated cookies/session
- Import the session into ZAP
- Use the imported session for testing
This approach requires re-authentication when the session expires.
OAuth and OpenID Connect
Testing applications using OAuth or OpenID Connect:
Using the OAuth Add-on
- Install the OAuth Support add-on
- Configure the OAuth settings:
- Client ID and Secret
- Authorization and Token endpoints
- Redirect URI
- Scopes
- ZAP will handle the OAuth flow automatically
Script-Based OAuth Handling
For complex OAuth scenarios:
- Create a script-based authentication script
- Implement the OAuth flow:
- Authorization request
- Token exchange
- Token refresh
- Store and use the access token
JWT Authentication
Many modern applications use JSON Web Tokens (JWT) for authentication:
Using the JWT Support Add-on
- Install the JWT Support add-on
- The add-on provides:
- JWT token detection
- Token decoding and analysis
- Token fuzzing capabilities
- Signature verification testing
Script-Based JWT Handling
For applications using JWT:
- Create an authentication script that:
- Performs the login
- Extracts the JWT token
- Adds the token to subsequent requests
- Optionally, implement token refresh logic
Troubleshooting Authentication
Authentication Verification Issues
If ZAP cannot determine authentication status:
-
Check Indicators:
- Ensure logged-in/out indicators are correct
- Use regex patterns that reliably appear/disappear
- Test patterns with the "Find..." feature in responses
-
Verify Response Content:
- Check if the application returns different content when authenticated
- Some applications use status codes or headers instead of body content
-
Use Script-Based Verification:
- Implement custom verification logic in a script
- Check specific elements, headers, or response characteristics
Best Practices
Test with Multiple Users
Create multiple users with different roles to:
- Test role-based access controls
- Identify privilege escalation issues
- Verify proper authorization checks
Maintain Authentication State
- Monitor for session expiration
- Implement re-authentication when needed
- Use appropriate session management methods
Secure Credential Handling
- Don't commit real credentials to scripts
- Use test accounts with limited privileges
- Consider environment variables or secure storage for credentials
Combine Manual and Automated Testing
- Use automated authentication for repetitive testing
- Perform manual testing for complex authentication flows
- Verify authentication security controls manually
Next Steps
Now that you understand authentication techniques in OWASP ZAP, explore these related topics:
- Scripting - Create custom scripts for authentication and session management
- API Security Testing - Test API authentication and authorization
- Automation - Automate authenticated scanning
- Best Practices - Best practices for effective and ethical use of ZAP