简体   繁体   中英

Gatling - decode JWT token and verify value in token

I am with Gatling tests in Scala and want to verify some fields in the decoded JWT token. I know how to decode it, but it is not possible/very slow to map the resulting JSON to an entity with Jackson like I did in Java, to check the value and/or existence.

I do some HTTP request and get a JWT token in JSON, like:

{"id_token":"xxxxxxx...."}

The token is JWT; I can decode it to get another JSON:

JWSObject jwsObject = JWSObject.parse(authorizeToken); // from com.nimbusds.jose.JWTObject
log.info("Decoded JWS object: {}", jwsObject.getPayload().toString());

It gets me:

{
    "sub": "c3f0d627-4820-4397-af20-1de71b208b15",
    "birthdate": "1942-11-08",
    "last_purchase_time": 1542286200,
    "gender": "M",
    "auth_level": "trusted",
    "iss": "http:\/\/somehost.com",
    "preferred_username": "test6@app.com",
    "given_name": "test6",
    "middle_name": "test6",
    "nonce": "random_string",
    "prv_member_id": 146794237,
    "aud": "some_issuer",
    "nbf": 1546869709,
    "is_premium": true,
    "updated_at": 1540812517,
    "registered_time": 1527677605,
    "name": "test6 test6 test6",
    "nickname": "test6",
    "exp": 1546870708,
    "iat": 1546869709,
    "family_name": "test6",
    "jti": "838bdd3f-1add-46f5-b3a1-cb220d3547a6"
}

In Java I define a DTO and convert this JSON to an instance of DTO and checks the value of each field with Assert.assertEquals() or something.

But, in Gatling, it is not possible:

  • The conversion with Jackson is very slow, it takes me forever.
  • The check() call is chained and cannot work like org.junit.Assert .

I am with:

  http(...).exec(...)
    .check(
      header(HttpHeaderNames.ContentType).is("application/json;charset=UTF-8"),
      jsonPath("$..id_token") exists,
      jsonPath("$..id_token").saveAs("id_token"),
      status.is(200),
    )
  )
  .exitHereIfFailed
  .exec(session => {
    val token = session("id_token").as[String]
    log.debug("Token: " + token)
    val decodedToken:String = JWSObject.parse(token).getPayload.toString()
    val dto:JWTPayloadDTO = JsonUtil.fromJson(decodedToken)  // this is very slow

    // here verification

    log.info("JWT payload: " + dto)
    session
  }

So, what can I do? check() will not work in session => {} part.

JsonUtil.fromJson() :

package xxx.helpers

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.collection.mutable.ListBuffer

object JsonUtil {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def fromJson[T](json: String)(implicit m : Manifest[T]): T = {
    mapper.readValue[T](json)
  }


}

The DTO:

package xxx.dto

import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming

@JsonNaming(classOf[PropertyNamingStrategy.SnakeCaseStrategy])
case class JWTPayloadDTO(
  aud:                String,
  iss:                String,
  exp:                Long,
  nbf:                Long,
  iat:                Long,
  sub:                String,
  authLevel:          String,
  jti:                String,
  nonce:              String,

  preferredUsername:  String,
  name:               String,
  givenName:          String,
  familyName:         String,
  middleName:         String,
  nickname:           String,
  profile:            String,
  picture:            String,
  website:            String,
  email:              String,
  emailVerified:      Boolean,
  gender:             String,
  birthdate:          String,
  zoneInfo:           String,
  locale:             String,
  phoneNumber:        String,
  phoneNumberVerified:Boolean,
  mobileNumber:       String,
  updatedAt:          Long,
  registeredTime:     Long,
  prvMemberId:        Long,
  fbUid:              String,
  lastPurchaseTime:   Long,
  isPremium:          Boolean,
  isStaff:            Boolean
)

At first I resort to Sonartype for dependency resolving, as the repo readme suggests:

https://github.com/FasterXML/jackson-module-scala

sonatype.sbt :

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

And then add dependency in build.sbt .

Then I enter the module's wiki page and changed it to Maven(deleted sonatype.sbt )

https://github.com/FasterXML/jackson-module-scala/wiki

only in build.sbt :

libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-scala_2.12" % "2.9.8" // latest

Now it begins to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM