I'm attempting to test an HTTP service with JMeter. The HTTP service requires authentication through a simple bearer token mechanism. I'm trying to proceed as follows:
So far I've been able to post the request, get the token, extract it with regex, save it to a variable, and assert that the variable is appropriately set.
The problem is getting the variable into the HTTP header. In the "Header Manager" the value is set like this:
Unfortunately when the next requests are issued their authorization header has the value "Bearer ". Searching around the internet led me to believe that headers are configured before the thread starts, which would explain the "Bearer "
My sampling/grouping/nesting is as follows:
All the tests pass up to get restricted resource, which fails with a 400, since the authorization header is malformed.
I feel like I'm missing something really obvious, and/or approaching this problem the wrong way.
You can dynamically construct your authorization header using Beanshell PreProcessor as follows:
Add empty HTTP Header Manager as a child of your request which requires authorization
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 instancevars
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.