How to implement Basic Auth using Karate?
Asked Answered
L

1

6

I saw details about OAuth2 in Karate Demo. Can you also provide how to implement Basic Auth?

screenshot

Leftward answered 9/7, 2018 at 11:42 Comment(0)
N
13

Yes, this JS function is all you need (basic-auth.js):

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

And then use this function to build the value of the Authorization header:

* header Authorization = call read('basic-auth.js') { username: 'john', password: 'secret' }

Refer to the docs here: https://github.com/intuit/karate#http-basic-authentication-example

For OAuth or "login form" kinds of flows, see: https://mcmap.net/q/1770288/-how-to-setup-oauth-1-0-authentication-with-karate-for-twitter-duplicate and https://mcmap.net/q/1770289/-does-karate-dsl-framework-have-the-capability-to-pass-a-post-request-as-a-url-encoded-format

Nonrestrictive answered 9/7, 2018 at 13:0 Comment(4)
This function was a great help, but it didn't work for me for some reason. I had to modify this line: var encoded = Base64.getEncoder().encodeToString(temp.bytes); to: var encoded = Base64.getEncoder().encodeToString(temp.getBytes());Trailer
@PeteLoggie thanks, I edited the answer. this happened when we changed the JS engine in 1.X: github.com/intuit/karate/wiki/…Nonrestrictive
Sry but what’s creds in above?Ridglea
@avdheshmaurya and for anyone else who wonders, the creds refers to the last parameter on the * header Authorization = call read('basic-auth.js') {username: 'john', password: 'secret'} line.Olen

© 2022 - 2024 — McMap. All rights reserved.