Search code examples
jmeterhttp-headersrequest-headers

JMeter dynamically change/overwrite HTTP Header value?


I've been bumping my head around how to authenticate, get the token and pass it to following requests. And I solved it.

My JMeter script gets the token from response using JSON Extractor. And then I can set in HTTP Header Managers of following requests Authorization Bearer ${my_token} as on screenshot enter image description here And all good!

But when the scrip was recorded from the browser each request that follows authentication did record the token that been valid at that moment. Each request does have this: enter image description here Of course I could either edit source file of my script and replace there Bearer 98PTo3dqwT8qtgKxYaI2. ... 3d8i5Bc with Bearer ${my_token} or do the same in the GUI of JMeter. But that all isn't elegant and very not convenient whenever more new thread groups needs to be added or old re-recorded.

Is there a way to script e.g. in BeanShell PostProcessor a tiny script that would "say" that from this moment all following HTTP Header Manager's having Authorization = Bearer ${my_token}?

That way you do it once in the script and no troubles with changes. Or is there a way to achieve the same by playing HTTP Header Manager, or any other module?

Or same must be accomplished with philosophically different approach?

I tried this in BeanShell PostProcessor

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

And that works! But that I'd need to do for each following request - which does defeats the purpose as easier to add a variable right to each header.

Is there a way to command that "after this line all headers have their value of Authorization overwritten to new value"?

Thank you


Solution

    1. Be aware of JMeter Scoping Rules, it's enough to have one single HTTP Header Manager at the same level as your HTTP Request samplers and it will add your header to all of them

    2. Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, using Beanshell is some form of a performance anti-pattern

    3. Consider removing existing header as you may end up with having 2 Authorization headers and who knows which one will be sent and processed

    4. It might also be a good idea to check whether current sampler is HTTP Request sampler as not all Samplers respect the Header Manager. Something like:

      if (sampler instanceof org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy) {
          def headerManager = sampler.getHeaderManager()
          if (headerManager != null) {
              headerManager.removeHeaderNamed('Authorization')
              sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("Authorization", "Bearer " + vars.get("my_token")));
          }
      }