apreg
apreg

Reputation: 637

Karate - switch between headers

Presume I have 2 users and I use basic authentication. I'd like to generate the 2 basic auth tokens once and reuse it per scenario in one feature. On top of that I have scnearios where no authorization is needed. How could I achieve this with the least biolerplate? Currently I have

auth-header.js

function(creds) {
  var temp = creds.username + ':' + creds.password;
  var Base64 = Java.type('java.util.Base64');
  var encoded = Base64.getEncoder().encodeToString(temp.bytes);
  return 'Basic ' + encoded;
}

karate-config.js

...
config.apitester1AuthHeader = 
karate.call('classpath:auth-headers.js', {username:'apitester1', password:'xxx'});
config.apitester2AuthHeader = 
karate.call('classpath:auth-headers.js', {username:'apitester2', password:'xxx'});
...

project-get.feature

Feature: project end-point

Background:
* url baseUrl
Scenario: get projects user has right to
  * configure headers = {Authorization : '#(apitester1AuthHeader)'}
  Given path 'project'
...

Upvotes: 1

Views: 316

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

What you have looks reasonable.

Note that if you do:

* configure headers = null

It will have the effect of temporary no authorization. I would recommend stick with what you have and it is quite modular already.

Upvotes: 1

Related Questions