When conducting performance testing, it's vital to simulate user behavior as accurately as possible. A typical scenario involves testing a JWT-protected API over an extended period, which presents a challenge when the token has a short expiration time. In this blog post, we'll discuss how to create a realistic test in JMeter for an API that retrieves invoices and is protected by JWT, focusing on the efficient use of the refresh token mechanism.
We aim to test an API endpoint (/invoices
) that requires a valid JWT token. This token is initially obtained via a /users/login
endpoint but only remains valid for 300 seconds. We'll use the /users/refresh
endpoint to avoid frequent logins to renew the token.
Here are the steps to set up this test in JMeter:
${__jexl3(${tokenGenerationTimestamp} == 0,)}
to check if tokenGenerationTimestamp is set. This variable holds the timestamp of the last token generation./users/login
.vars.put("tokenGenerationTimestamp", "${__time(,)}")
. This records the time of token acquisition.${__jexl3((${__time(,)} - ${tokenGenerationTimestamp}) > (${EXPIRES_IN} * 900))}
. Here, EXPIRES_IN is the duration in seconds, and 900 represents 90% of the expiration time./users/refresh
to obtain a new token./invoices
.Authorization
header to Bearer ${TOKEN}
to pass the JWT token.Using the refresh token endpoint instead of repeatedly hitting /users/login
more accurately simulate real user behavior. In real-world scenarios, applications don't login each time they need to access a JWT-protected resource; they refresh the token when needed. This approach also helps identify potential issues with the token refresh mechanism and ensures the stability and performance of the API under prolonged use.
Implementing this testing strategy in JMeter can create more realistic and efficient performance tests for JWT-protected APIs. It avoids overloading the login endpoint and gives insights into the performance of the token refresh mechanism and the protected API under continuous access.
Delen: