1

I am learning the Gatling tool and stuck in developing scenarios for Secure Http API calls. I have created a scenario in which I am able to get the bearer token and save it in the variable(Token), but the variable(Token) is not passing its value in the authorization header.

Here's my code pleaser review it,

The value of the token variable is not getting by the following code line, .authorizationHeader(s"Bearer $token")

======================================================


import io.gatling.core.Predef._

import io.gatling.http.Predef._

import scala.concurrent.duration._

import scala.collection.JavaConversions._


class SampleToken2 extends Simulation {




  //Token define
  
  private var token: String = ""
  
  val auth = scenario("Retrieve Token")
    .exec(
      http("POST Auth Req")
        .post("http://iserver:9092/login")
        .body(ElFileBody("bodies/inventalogin.json")).asJson
        .check(bodyString.saveAs("Auth_Response"))
        .check(status.is(200))
        .check(jsonPath("$.token").find.saveAs("accesskey")))
    .exec{session => { token = session("accesskey").as[String]
      session}}
  

  

  //Header Define  
  
  val httpConf = http
    .baseUrl("http://iaserver:9092")
    .authorizationHeader(s"Bearer $token")
    .acceptHeader("application/json, */*")
    .acceptCharsetHeader("UTF-8") // Here are the common headers
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-UK,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")
    .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0")
    .shareConnections
    .proxy(Proxy("localhost", 8888).httpsPort(8888))


    def  myTestObjectMethod = {
      exec { session => println("token print2"); session }
      exec { session => println(token:String); session }
      exec(http("Get all devices with pagination")
        .get("/devices/getAllDevices?page=0&size=200")
        .check(status.in(200 to 210)))
        .pause(1, 20)
    }



  val scn = scenario("my_actual_load_test").exec(myTestObjectMethod)



  setUp(
    auth.inject(constantUsersPerSec(1) during (1 seconds)),
    scn.inject(nothingFor(2 seconds),
      constantUsersPerSec(50) during (300 seconds)
    )
    .protocols(httpConf))
    .assertions(global.responseTime.max.lt(500)) 
    .assertions(forAll.failedRequests.percent.lte(1)) 
    .assertions(global.responseTime.mean.lte(100))

}

Fouad Ilyas
  • 11
  • 1
  • 4

2 Answers2

0

Your token is not getting used because you're transferring it to a standard scala variable rather than just passing it through the session.

Gatling builders are executed once at startup, so when your httpConf references $token it's getting the value from that var at a time before any requests have been made - hence the value of token will be "".

Since you seem to want one call to get a token that is then used by all users in the second scenario, you need to load the value in the token var into the session and update you header httpConf to use the Gatling EL (which will pull the value from the session)

val httpConf = http
.baseUrl("http://iaserver:9092")
.authorizationHeader("Bearer ${token}")
.acceptHeader("application/json, */*")
...

def  myTestObjectMethod = {
  exec(session => session.set("token", token)
  .exec(http("Get all devices with pagination")
    .get("/devices/getAllDevices?page=0&size=200")
    .check(status.in(200 to 210))
  )
  .pause(1, 20)
}
James Warr
  • 2,552
  • 2
  • 7
  • 20
  • Thank you for the reply. I did what you guided me. I am getting an error ==> 10:36:57.562 [ERROR] i.g.h.a.HttpRequestAction - 'httpRequest-11' failed to execute: No attribute named 'token' is defined. If you look into my code (Token define) I am trying to save the token in accesskey and then save the accesskey value to token variable. Is there any way to get the vale of accesskey in myTestObjectMethod ? Actually the API is secured by Bearer auth and I am unable to add/pass bearer token in API call. – Fouad Ilyas Aug 21 '20 at 05:40
  • Can you provide me the code for testing secured token bearer API in scala Gatling? It would be helpful for me to understand the whole situation. – Fouad Ilyas Aug 21 '20 at 06:53
  • @FouadIlyas you saved it as `accesskey`, why are you accessing it with the name `token`? – George Leung Aug 21 '20 at 09:28
-1

Got my answer from the below link: Gatling Scala:Unable to send auth token to the method using session variable

I need to pass the token method in the scenario in order to get the token in the session.



  val authAPI = exec(
    exec(
      http("POST Auth API")
        .post("http://iserver:9092/login")
        .body(ElFileBody("bodies/inventalogin.json")).asJson
        .check(bodyString.saveAs("Auth_Response"))
        .check(status.is(200))
        .check(jsonPath("$.token").find.saveAs("token")))
      exec{session => { tokenAPI = session("token").as[String]
      session}}

var headers_10 = Map("Content-Type" -> """application/json""", "Authorization" -> "Bearer ${token}")

  def  getAllDevices() = {
    exec { session => println("token print2"); session }
    exec { session => println(tokenAPI:String); session }
    exec(session => session.set("token", tokenAPI))
    exec(http("Get all devices")
      .get("/devices/getAllDevices")
      .headers(headers_10)
      .check(status.in(200 to 210)))
      //.exec { session => println(session); session }

      .pause(1, 20)
  }

// Scenario Definition
  val scn = scenario("Basic")
    .exec(authAPI)
    .pause(1)
    .exec(getAllDevices())
    .pause(1)
    .exec(getAllDevicesPagination())
    .pause(1)
    .exec(logintest())


Fouad Ilyas
  • 11
  • 1
  • 4