Missing header in Karate in spite of "configure headers"

22 views Asked by At

We have added a Keycloak authentication to our project, and I'm having trouble setting up my tests so that I can run them with authenticated users. The configure headers to set an authentication header does not seem to have any effect.

I have created one file with the code that fetches an authentication token and sets a header for following requests:

keycloak-auth.feature

Feature: Keycloak authentication
  # 'keycloakUrl' and 'keycloakClientId' are set in karate-config.js

  Scenario: Get access token
    Given url keycloakUrl
    And path 'token'
    And form field username = username
    And form field password = username
    And form field grant_type = 'password'
    And form field client_id = keycloakClientId
    When method post
    Then status 200
    And configure headers = { Authorization: #('Bearer ' + response.access_token) }

A test file now looks like this:

test.feature

Feature: DELETE tests with myuser1

  Background:
    ... variable definitions, set url ...

    # only needed once, all tests in this file should run with the same user
    * karate.callSingle('classpath:feature/keycloak-auth.feature', { username: 'myuser1' })

  Scenario: DELETE a market that does not exist
    Given path 'markets', 'abc123'
    When method delete
    Then status 404

... more Scenarios ...

When I run this file, I see that the request to Keycloak happens and returns a 200 response including an access_token field, so the callSingle is set up correctly. However, my DELETE request in the actual test does not have any Authorization header:

1 > DELETE http://localhost:23115/api/markets/abc123
1 > Host: localhost:23115
1 > Connection: Keep-Alive
1 > User-Agent: Apache-HttpClient/4.5.14 (Java/21.0.1)
1 > Accept-Encoding: gzip,deflate

... and therefore fails. Why does the configure headers not add the header?

1

There are 1 answers

1
Peter Thomas On

Try making this change:

And configure headers = { Authorization: 'Bearer ' + response.access_token }

The #(foo) approach would possibly get re-evaluated.