B4J Code Snippet [B4X] Get JWT Payload (JavaWebToken)

This function reads the payload of a jwt token and returns a map

Input token:
B4X:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2xsZWN0aW9uSWQiOiJfcGJfdXNlcnNfYXV0aF8iLCJleHAiOjE3Mzc4NDc5MjksImlkIjoiNzA4MXNoeDM3YzY3dmUzIiwicmVmcmVzaGFibGUiOnRydWUsInR5cGUiOiJhdXRoIn0.W0ZA6c2_qKhbjjvnUKDJPfO-kU-_prk235_YU8fYBxU
Payload from this token:
1737243159881.png


B4X:
Public Sub GetJWTPayload(Token As String) As Map
    Dim su As StringUtils
    Dim parts() As String = Regex.Split("\.", Token)
    Dim ResultMap As Map
    ResultMap.Initialize
    
    Dim b() As Byte = su.DecodeBase64(IIf(parts(1).Contains("="),parts(1),parts(1) & "="))
    ResultMap.Put("Payload",BytesToString(b, 0, b.Length, "UTF-8").As(JSON).ToMap)
    
    Return ResultMap
End Sub
 

aeric

Expert
Licensed User
Longtime User
I tried to decode my JWT token with your function but failed.
Asking Gemini, I found the fix.

Understanding Base64 Padding
In Base64 encoding, padding with equal signs ("=") is crucial. Here's why:
  • Grouping: Base64 encodes data in groups of 3 bytes. Each group is then translated into 4 characters.
  • Padding's Role: If the original data isn't a multiple of 3 bytes, padding is added to ensure the final encoded string is a multiple of 4 characters.
Manual Padding Steps
  1. Determine Padding Length:
    • Calculate the length of the encoded string modulo 4.
    • If the result is 0, no padding is needed.
    • If the result is 2, add "==".
    • If the result is 3, add "=".
  2. Add Padding:
    • Append the appropriate number of "=" signs to the end of the encoded string.
Here is my code:
B4X:
Public Sub GetJWTPayload (Token As String) As Map
    Dim parts() As String = Regex.Split("\.", Token)
    Dim encoded As String = parts(1)
    Select encoded.Length Mod 4
        Case 2
            encoded = encoded & "=="
        Case 3
            encoded = encoded & "="
    End Select
    Dim su As StringUtils
    Dim b() As Byte = su.DecodeBase64(encoded)
    Dim payload As String = BytesToString(b, 0, b.Length, "UTF-8")
    Return payload.As(JSON).ToMap
End Sub
 
Top