Search code examples
jmeterbeanshell

Extract a key from a Base64 decoded string


I am trying to decode a base 64 format string in JMeter, with a BeanSheel PostProcessor, and extract the nameid from the string, which (nameid) I am further going to use in sending another request.

I tried the following code but it doesn't work.

import org.apache.commons.codec.binary.Base64;

String decoded_response = new String(Base64.decodeBase64(data));
String memberId = decoded_response.nameid;
log.info("memberid", memberId)

It is giving me errors as:

ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.commons.codec.binary.Base64;  String decoded_response = new St . . . '' : Typed variable declaration : Cannot access field: nameid, on object: iDzÏí¢G§{"typ":"JWT","alg":"HS256"}{"nameid":"1862","unique_name":"user1@mywebsite.com","iss":"http://mywebsite-app.azurewebsites.net/","aud":"414e1927a3884f68abc79f7283837fd1","exp":1635435731,"nbf":1635349331}$S‘­vC‡öRé™v„2xÉr}ïK…u®KŸäpÏƯ-¢G§þÜ©y·š­êÞƘ«zÏâŸÎ·÷Ö¬rXžžßâvx

Basically here I want to decode the token and get some of the id fields to be used in further requests. What is a good way of doing this? Is there any alternative to store the nameid in another variable and use it further in another request?


Solution

    1. You need to decode Base64URL, not Base64
    2. If it succeeds you will get JSON which needs to be parsed
    3. Since JMeter 3.1 you're supposed to use JSR223 Test Elements and Groovy language for scripting

    So I think you need to change your code to something like:

    def response = prev.getResponseDataAsString()
    
    def parts = response.split('\\.')
    
    def part2 = org.codehaus.groovy.runtime.EncodingGroovyMethods.decodeBase64Url(parts[1])
    
    def nameid = new groovy.json.JsonSlurper().parse(part2).nameid
    

    More information: