Using Karate's callonce for Reusable Authentication Setup
Learn how to eliminate duplicate login steps in Karate API tests by centralizing authentication with the callonce keyword, then verify the result with the HTML report.
25 Jun 2026, 15:39 UTC

Desired outcome
Create a Karate test suite where a single authentication request runs once per test execution and its token is reused across multiple scenarios, reducing duplication and improving maintainability.
Prerequisites
- Java JDK 11 or later installed and
JAVA_HOMEset. - Apache Maven 3.6+ available on the PATH.
- A running API endpoint that supports a login operation returning a JSON Web Token (JWT) or similar bearer token.
- Basic familiarity with Karate’s Gherkin‑style syntax (Given, When, Then).
Procedure
- Add the Karate dependency to your
pom.xml. Place this inside the<dependencies>section:
<dependency>
<groupId>com.intuit.karate</groupId>
<artifactId>karate-junit5</artifactId>
<version>1.4.0</version>
<scope>test</scope>
</dependency>
Run mvn clean install to download the libraries. This step modifies the local Maven repository; you can revert it by deleting ~/.m2/repository/com/intuit/karate if needed.
auth.feature under src/test/resources:Feature: Obtain auth token
Background:
* url 'https://api.example.com'
Scenario: Successful login
Given path '/auth/login'
And request { username: '#(username)', password: '#(password)' }
When method post
Then status 200
And def token = response.token
And karate.configure('headers', { Authorization: 'Bearer #' + token })
This feature expects two variables, username and password, to be defined before it is called.
karate-config.js file in the test resources folder to supply credentials once for the whole suite:function fn() {
return {
username: 'test_user',
password: 'Secret123!'
};
}
callonce to execute the authentication only once:Feature: User profile API
# The callonce runs the auth.feature before any scenario in this file
* callonce read('classpath:auth.feature')
Scenario: Retrieve own profile
Given path '/users/me'
When method get
Then status 200
And match response.id == '#notnull'
Scenario: Update profile
Given path '/users/me'
And request { firstName: 'Updated', lastName: 'User' }
When method put
Then status 200
And match response.firstName == 'Updated'
The callonce keyword ensures that the login scenario from auth.feature executes a single time, and the configured headers (including the Bearer token) persist for all subsequent scenarios in the same file.
mvn test
Execute this command in the project root. No special OS privileges are required beyond the ability to read the project files and write to the target directory.
- Check the console output for lines similar to:
[karate] 1: Scenario: Successful login [karate] 2: Given path '/auth/login' [karate] 3: ... [karate] 10: status 200 [karate] 11: def token = response.xxx [karate] 12: karate.configure('headers', { Authorization: 'Bearer xxx' })Notice that the login scenario appears only once, even though two scenarios follow.
- Open the generated HTML report at
target/karate-reports/karate-summary.html. Each scenario should show a green pass, and the report will list the authentication step under the “Background” section of the report. - Optionally, inspect the request logs (if you enabled Karate’s
configure sslorconfigure logPrettyRequest) to confirm that theAuthorizationheader contains the token on the subsequent calls.
- Remove the Karate dependency from
pom.xmland runmvn cleanto delete downloaded artifacts. - Delete the
auth.feature,karate-config.js, and any test feature that usedcallonce. - Commit or stash these changes, then revert to the previous commit if you are using version control.
Limitations and practical checks
callonceworks per‑feature file. If you split tests across multiple files, each file will re‑run the authentication unless you move thecallonceto a common file andcallit from each test file.- Complex JavaScript expressions inside the authentication feature (e.g., token manipulation) can reduce readability. Keep the logic simple; move heavy processing to a separate Java utility if needed.
- To confirm that the token is actually being sent, add a temporary
print tokenline after thedef tokenstep and re‑run the test; remove the print before committing.
Conclusion
By centralizing authentication with Karate’s callonce keyword, you avoid repetitive login steps, improve test execution speed, and maintain a single source of truth for credentials. Verify the behavior through console logs and the HTML report, and roll back by removing the added files and dependency if the approach does not suit your project’s structure.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.