Mahesh S
Mahesh S

Reputation: 61

How to manually set a cookie in JMeter that is set programmatically by JavaScript

I am testing a web application which has a following flow :

  1. User logs in
  2. On successful login, an access token is issued.
  3. Every request after login has the access token to get a resource.

In my JMeter test plan, I added a cookie manager and I could extract this access token from the response header of the login request. I want to set this access token as a cookie the test plan.

I added this after extracting the access token in a BSF PostProcessor : vars.put('COOKIE_access_token', actual_token); and it is seen as a cookie variable in the debug sampler.

enter image description here

But the subsequent requests after login do not have this access token in their cookie data, and as a result are again redirected to login page.

How can I set this token as a cookie which will be used for all further requests?

Upvotes: 3

Views: 9018

Answers (2)

user13466899
user13466899

Reputation: 1

import org.apache.jmeter.protocol.http.control.Cookie;

sampler.getCookieManager().add(new Cookie("access_token", "actual_token", "domain", "path", true, Long.MAX_VALUE));

This code really worked. This helped me.
Who ever wants to pass missing cookie(session or any cookies) in request cookie data , instead of adding header manager please use the above code in bean shell pre processor.

Thank you DMITRI T

Upvotes: 0

Dmitri T
Dmitri T

Reputation: 168002

Defining variable does not add the cookie itself. You need to insert cookie into Cookie Manager to make this work, like:

  1. Add a Beanshell PreProcessor as a child of the request which fails
  2. Put the following code into the PreProcessor's "Script" area:

    import org.apache.jmeter.protocol.http.control.Cookie;
    
    sampler.getCookieManager().add(new Cookie("access_token", "actual_token", "domain", "path", true, Long.MAX_VALUE));
    

Replace domain, path, true (stands for "secure") and Long.MAX_VALUE (expires) with your own values.

See How to Use BeanShell: JMeter's Favorite Built-in Component for example of manipulating cookies programatically.

Upvotes: 6

Related Questions