Vawani
Vawani

Reputation: 399

Jmeter with basic authentication

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.

Upvotes: 2

Views: 5877

Answers (2)

UBIK LOAD PACK
UBIK LOAD PACK

Reputation: 34516

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.

Upvotes: 2

Dmitri T
Dmitri T

Reputation: 168002

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

Upvotes: 4

Related Questions