Q7 of 40 · Karate

How does Karate handle authentication (e.g. bearer token in headers)?

KarateJuniorkarateauthenticationbearer-tokenheadersfundamentals

Short answer

Short answer: Set a header variable in Background with * def authHeader = { Authorization: 'Bearer ' + token } and apply it with And headers authHeader in each scenario. For token retrieval, call a login feature with * def auth = call read('classpath:helpers/login.feature') and extract the token from auth.token.

Detail

Inline header — simple cases:

Background:
  * def token = 'static-test-token'
  * header Authorization = 'Bearer ' + token

Using * header X = value sets the header for all subsequent requests in the scenario.

Header object — for multiple headers:

* def authHeaders = { Authorization: 'Bearer ' + token, 'X-Tenant': 'tenant-1' }
* headers authHeaders

Token from a login feature — dynamic auth:

* def auth = call read('classpath:helpers/login.feature')
* def token = auth.accessToken
* header Authorization = 'Bearer ' + token

The login.feature POSTs to the token endpoint and returns the access token:

Feature: Login helper
  Scenario: Get access token
    Given url tokenUrl
    And   form field username = credentials.username
    And   form field password = credentials.password
    When  method POST
    Then  status 200
    * def accessToken = response.access_token

karate-config.js — centralise auth for all features:

var auth = karate.call('classpath:helpers/login.feature');
return { authHeader: 'Bearer ' + auth.accessToken };

// EXAMPLE

protected-api.feature

Feature: Protected endpoints require authentication

  Background:
    * url karate.properties['api.base.url']
    # Call login helper and capture token once per feature
    * def auth = call read('classpath:helpers/login.feature')
      { username: 'testuser', password: 'testpass' }
    * header Authorization = 'Bearer ' + auth.accessToken

  Scenario: Access protected profile endpoint
    Given path '/me'
    When  method GET
    Then  status 200
    And   match response.username == 'testuser'

  Scenario: Access protected admin endpoint — forbidden for regular user
    Given path '/admin/users'
    When  method GET
    Then  status 403

// WHAT INTERVIEWERS LOOK FOR

Setting headers via Background, using a login helper feature to fetch a real token (not hard-coding), and centralising the token in karate-config.js so all features share it. Knowing the difference between * header (single) and * headers (map) is a concrete detail.

// COMMON PITFALL

Hard-coding a static token string in the feature file — this fails when the token expires and leaks credentials into version control. Always load tokens dynamically from karate-config.js or a called feature.