Authorization with a dynamic access token is used to pass dynamic response content to subsequent requests. This is used to validate API authorization.
In this post, we will discuss fetching an access token (dynamic response) with the help of JSON Extractor. We will also show how to pass it as a parameter in the subsequent request using BeanShell Assertion.
To achieve authorization with access token, we need to create 2 Thread Groups:
Thread Group 1 – To generate Access Token Thread Group 2 – To pass Access Token to Request
Prerequisite:
Install JMeter on your system.
Implementation Steps:
Step 1 – Add Thread Group 1: Thread Group – Authorization Token Generation
1. Add Thread Group
We should provide the name of the Thread Group. In this case, this thread group is used to generate the token, so named Token Generation. We want to generate only 1 token, so the Number of Threads, Ramp-up period, and Loop Count are 1 only.
2. Add HTTP Request Sampler
In the HTTP Request Control Panel, the Path field indicates which URL request you want to send
To add:Right-clickon Thread Group and select: Add -> Sampler -> HTTP Request
Add valid credentials in the parameters section.
3. Add HTTP Header Manager
The Header Manager lets you add or override HTTP request headers like can add Accept-Encoding, Accept, Cache-Control
To add: Right-click on Thread Group and select: Add -> Config Element -> HTTP Read Manager
Add Authorization as Headers in Header Manager
4. Add JSON Extractor
To extract the authentication token from the request, we are going to use JMeter JSON Extractor. The process of extracting a variable from a response works as mentioned below:
First, the server sends back a response. Then a post-processor, like the JSON Extractor, executes. It extracts part of the response and puts it into a variable like ${token}.
To add:Right-click on Thread Group and select: Add -> Post Processors -> JSON Extractor
The JSON extractor requires us to follow a few steps, so we can process the JSON correctly.
1) Name – JSON Extractor 2) Apply to – we will use the defaulted Main Sample Only. The option is: The main sample only – the assertion only applies to the main sample 3)Name of created variables– BEARER 4) JSON Path Expressions – access_token
5. Add BeanShell Assertion
An advanced assertion with full access to JMeter API. Java conditional logic can be used to set the assertion result.
To add:Right-click on Thread Group and select: Add -> Assertions -> BeanShell Assertions
Add the below-mentioned script in the Script section of BeanShell Assertion
${__setProperty(BEARER, ${BEARER})};
Step 2 – Add Thread Group 2: Thread Group – Main Request
1. Add Thread Group
Provide a name to this Thread Group. I have also provided the number of threads, ramp-up, and duration in the thread group as shown in the image
We can parameterize the values of the number of threads. We can also do this for the ramp-up period and duration. This is done using a JMeter property called ___P. You can ask why we are using the property function in JMeter. It is because this makes the JMeter script configurable. We can pass any value through the command line without making any changes in the script.
___P – This is a simplified property function that is intended for use with properties defined on the command line.
If no default value is supplied, it is assumed to be 1. The value of 1 was chosen because it is valid for common test variables such as loops, thread count, ramp-up, etc.
${__P(group1.threads)} – return the value of group1.threads
${__P(THREADS,1)} – This THREADS value will be passed through command line. If no value is passed, by default, it will choose 1.
Similarly, ramp-up and duration are parameterized.
Below-mentioned are the values used in HTTP Request to perform the test
Add a valid request body in the Body Data section (if the request is POST).
3. Add HTTP Header Manager
We have previously extracted the token from the Token Generation request. Now, it’s time to reuse it in the header section of HTTP Header Manager.
Below are the values used in the HTTP Request to perform the test.
Authorization = Bearer ${__property(BEARER)}
Step 3 – Adding Listeners to the Test Plan
Listeners – They show the results of the test execution. They can show results in a different format such as a tree, table, graph, or log file
We have added listeners – View Result Tree
View Result Tree – View Result Tree shows the results of the user request in basic HTML format
To add: Right-click Test Plan, Add -> Listener -> View Result Tree
Step 4 – Save the Test Plan
To Save: Click FileSelect -> Save Test Plan as ->Give the name of the Test Plan. It will be saved as .jmx format.
Step 5 – Run the Test Plan
Click on Green Triangle as shown at the top to run the test.
Step 6 – View the Execution Status
Click on View Result Tree to see the status of Run. A successful request will be of a Green colour in the Text Section
Here, we can see that the Token Generation request is successfully processed.
The below image shows that the Main Request is successfully executed too.
Troubleshooting
Correct Authorization Setup
In JMeter, typically, we will use an HTTP Header Manager to include your access token in requests. Make sure the token is formatted correctly: `Authorization: Bearer `.
Understand the Authorization Type
Make sure correct type of authorization is required (e.g., Bearer Token) and how the access token should be included in requests (usually in the headers).
Network and Endpoint Checks
Check for firewall rules or network issues that might be blocking access.
Congratulation!! We can add an authorization token generated by a request add it to another request and process the request using JMeter.
Selects the specified property in a parent object.
[‘property’]
Selects the specified property in a parent object. Be sure to put single quotes around the property name.Tip: Use this notation if the property name contains special characters such as spaces, or begins with a character other than A..Za..z_.
[n]
Selects the n-th element from an array. Indexes are 0-based.
[index1,index2,…]
Selects array elements with the specified indexes. Returns a list.
..property
Recursive descent: Searches for the specified property name recursively and returns an array of all values with this property name. Always returns a list, even if just one property is found.
*
Wildcard selects all elements in an object or an array, regardless of their names or indexes.
[start:end] [start:]
Selects array elements from the start index and up to, but not including, end index. If end is omitted, selects all elements from start until the end of the array. Returns a list.
[:n]
Selects the first n elements of the array. Returns a list.
[-n:]
Selects the last n elements of the array. Returns a list.
[?(expression)]
Selects all elements in an object or array that match the specified filter. Returns a list.
[(expression)]
Script expressions can be used instead of explicit property names or indexes. An example is [(@.length-1)] which selects the last item in an array. Here, length refers to the length of the current array rather than a JSON field named length.
@
Used in filter expressions to refer to the current node being processed.
Below is the sample JSON which I am using for extraction examples. I have saved this file in resources/Payloads as test.json.
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
To extract all books present in the store:-
String allBooks = JsonPath.read(jsonString, "$..*").toString();
System.out.println("--------------- All books in the store --------------");
System.out.println(allBooks);
The complete program looks like as shown below:
import com.jayway.jsonpath.JsonPath;
public class JsonPath_Demo {
public static void main(String args[]) {
String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/test.json")));
String allBooks = JsonPath.read(jsonString, "$..*").toString();
System.out.println("--------------- All books in the store --------------");
System.out.println(allBooks);
}
}
The output of the above program is
Below are examples that show how to extract different nodes from a JSON Body. I have used the above JSON Body for these examples.
// All bicycles in the store
String allBicycles = JsonPath.read(jsonString, "$..bicycle").toString();
System.out.println("--------------- All bicycles in the store ---------------");
System.out.println(allBicycles);
// The number of books
String noOfBooks = JsonPath.read(jsonString, "$..book.length()").toString();
System.out.println("--------------- The number of books ---------------");
System.out.println(noOfBooks);
// The authors of all books
String authors = JsonPath.read(jsonString, "$.store.book[*].author").toString();
System.out.println("--------------- Author of all Books ---------------");
System.out.println(authors);
// All authors
String allAuthors = JsonPath.read(jsonString, "$..author").toString();
System.out.println("--------------- All Authors ---------------");
System.out.println(allAuthors);
// All details of the store
String store = JsonPath.read(jsonString, "$.store.*").toString();
System.out.println("--------------- All details of the store ---------------");
System.out.println(store);
// Price of store
String storePrice = JsonPath.read(jsonString, "$.store..price").toString();
System.out.println("--------------- price of store ---------------");
System.out.println(storePrice);
The output of the above program is
Below are the examples where I have extracted specific book (nodes) from the JSON body.
// Third book
String thirdBook = JsonPath.read(jsonString, "$..book[2]").toString();
System.out.println("--------------- third book ---------------");
System.out.println(thirdBook);
// first Last Book
String firstLastBook = JsonPath.read(jsonString, "$..book[-1]").toString();
System.out.println("--------------- first Last Book ---------------");
System.out.println(firstLastBook);
// first two Books
String firstTwoBooks = JsonPath.read(jsonString, "$..book[0,1]").toString();
System.out.println("--------------- first Two Books ---------------");
System.out.println(firstTwoBooks);
// books from index 0 (inclusive) until index 2 (exclusive)
String booksRange = JsonPath.read(jsonString, "$..book[:2]").toString();
System.out.println("--------------- books from index 0 (inclusive) until index 2 (exclusive) ---------------");
System.out.println(booksRange);
// All books from index 1 (inclusive) until index 2 (exclusive)
String booksRange1 = JsonPath.read(jsonString, "$..book[1:2]").toString();
System.out.println("------------ All books from index 1 (inclusive) until index 2 (exclusive) -----------");
System.out.println(booksRange1);
// Book number one from tail
String bottomBook = JsonPath.read(jsonString, "$..book[1:]").toString();
System.out.println("--------------- Book number one from tail ---------------");
System.out.println(bottomBook);
The output of the above program is
Filters are logical expressions used to filter arrays. Below are examples of a JSONPath expression with the filters.
// All books in store expensive than 10
String expensiveBook = JsonPath.read(jsonString, "$.store.book[?(@.price > 10)]").toString();
System.out.println("--------------- All books in store costlier than 10 ---------------");
System.out.println(expensiveBook);
// All books in store that are not "expensive"
String notExpensiveBook = JsonPath.read(jsonString, "$..book[?(@.price <= $['expensive'])]").toString();
System.out.println("--------------- All books in store that are not expensive ---------------");
System.out.println(notExpensiveBook);
// All books in store that are equal to price 8.95
String comparePrice = JsonPath.read(jsonString, "$.store.book[?(@.price == 8.95)]").toString();
System.out.println("--------------- All books in store that are not expensive ---------------");
System.out.println(comparePrice);
// All books matching regex (ignore case)
String regxExample = JsonPath.read(jsonString, "$..book[?(@.author =~ /.*REES/i)]").toString();
System.out.println("--------------- All books matching regex (ignore case) ---------------");
System.out.println(regxExample);
// All books with price equal to mentioned list of prices
String priceList = JsonPath.read(jsonString, "$..book[?(@.price in ['12.99', '8.99'])]").toString();
System.out.println("--------------- All books with price equal to mentioned list of prices ---------------");
System.out.println(priceList);
// All books with price NOT equal to mentioned list of prices
String excludePriceList = JsonPath.read(jsonString, "$..book[?(@.price nin ['12.99', '8.99'])]").toString();
System.out.println("---------- All books with price NOT equal to mentioned list of prices ---------");
System.out.println(excludePriceList);
// All books with specified substring (case-sensitive)
String substringExample = JsonPath.read(jsonString, "$..book[?(@.author contains 'Melville')]").toString();
System.out.println("--------------- All books with specified substring (case-sensitive) ---------------");
System.out.println(substringExample);
// All books with an ISBN number
String specificBook = JsonPath.read(jsonString, "$..book[?(@.isbn)]").toString();
System.out.println("--------------- All books with an ISBN number ---------------");
System.out.println(specificBook);
The output of the above program is
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!