JMeter Alter HTTP Headers During Test

See this forum post: http://www.jmeter-archive.org/Variables-in-HTTP-headers-td4579331.html

You need to move your login under a controller. In my case, I used an Only Once Controller. Then after the controller you can add the HTTP Header Manager with the Authorization header as "Bearer ${BEARER}" and it will read your variable. This is better than the other answer because then you don't need to duplicate the BeanShell PreProcessor under every request. My tree looked like this:

JMeter Tree


You can dynamically construct your authorization header using Beanshell PreProcessor as follows:

  1. Add empty HTTP Header Manager as a child of your request which requires authorization

  2. Add Beanshell PreProcessor as a child of the same request with the following code:

    import org.apache.jmeter.protocol.http.control.Header;
    
    sampler.getHeaderManager().add(new Header("Authorization","Bearer " + vars.get("BEARER")));
    

This will construct fully dynamic header using BEARER variable.

  • sampler is a shorthand to HTTPSamplerProxy class which gives access to parent Sampler instance
  • vars is the instance of JMeterVariables class which allows read/write access to all JMeter variables available within the bounds of current context (usually current Thread Group)

See How to use BeanShell: JMeter's favorite built-in component guide for more details on Beanshell scripting and kind of Beanshell cookbook.