Ana içeriğe geç

Extracting Data from JSON in Payload Field of Incoming JWT Key

Groovy Script

import groovy.json.JsonSlurper
import org.apache.commons.codec.binary.Base64

def authzHeaderValue = requestHeaderMapToTargetAPI.get("Authorization")
authzHeaderValue = authzHeaderValue.split('\\.')[1] //Bearer yazan kısım için, veri her zaman ilk nokta işaretinden sonra geçtiği için ayrılma ihtiyacı duyulmamıştır.

def decodedValue = new String(Base64.decodeBase64(authzHeaderValue),"UTF-8")
def jsonSlurper = new JsonSlurper()
def jsonMessage = jsonSlurper.parseText(decodedValue)

//do some logic with json:
requestHeaderMapToTargetAPI.put("usernameTest",jsonMessage.username)

Explanation

This script performs the following operations:

  1. Token Retrieval: JWT token is retrieved from Authorization header
  2. Payload Parsing: JWT token format is header.payload.signature. Token is split by dot (.) character and payload part (second section) is retrieved
  3. Base64 Decode: Payload part is Base64 encoded JSON format. This part is decoded
  4. JSON Parse: Decoded data is parsed as JSON
  5. Data Usage: Desired fields (e.g., username) are extracted and can be used

In the example, the username field within the payload is retrieved and added to the header as usernameTest.

not

This script should be run on the request line (Request Policy) because it uses the requestHeaderMapToTargetAPI variable.