2

I want to run a loadtest on a RestAPI which I can access via below java

        name = "username";
        String password = "password";
        String authString = name + ":" + password;
        byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); //
        String authStringEnc = new String(authEncBytes);
        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

But in jmeter I am not able add this, new to jmeter please help.

Vawani
  • 399
  • 10
  • 25

2 Answers2

3

You can use the same code to generate the encoded credentials:

  1. Add HTTP Header Manager as a child of the relevant HTTP Request sampler
  2. Add JSR223 PreProcessor as a child of the relevant HTTP Request sampler
  3. Put the following code into "Script" area

    name = "username";
    String password = "password";
    String authString = name + ":" + password;
    byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); //
    String authStringEnc = new String(authEncBytes);
    sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("Authorization", "Basic " + authStringEnc));
    
  4. Check Cache compiled script if available box

JMeter should now add the necessary "Authorization" header to your request.

JMeter Basic Authentication

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • Why was this voted down? Worked for me when the official JMeter auth manager didn't. Add "vars.get("appPassword");" if you don't want to hardcode passwords. – Shorn May 07 '18 at 05:33
  • Well explaind solution. Thank you. – Alex Zel Jun 11 '19 at 10:33
2

Since JMeter 3.2, Basic Auth is provided Out Of The Box using HttpClient4 implementation and configured by default, see:

HTTP HC4 Implementation now provides preemptive Basic Auth enabled by default

Just add HTTP_Authorization_Manager and fill in required information.

Example:

enter image description here

  • Configuration will be:

enter image description here

This configuration will match any request starting with "http://localhost:8081"

See also this question:

Although my answer is downvoted for I don't know which reason, it is the best way to setup Basic Auth. Scripting is no more required at all since 3.2.

UBIK LOAD PACK
  • 33,980
  • 5
  • 71
  • 116