Decode JWT (JSON Web Token) in Apex

A little bit about JWT Tokens

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

Here's a code snippet to decode a JWT Token

 String tempJWTToken ='eyJraWQiOiIwOE1XOU11bThySnc3VGdpRXM1R3M2ckZBUlpET0dBRyIsImFsZyI6IlJTMjU2In0.eyJkYXRhIjp7ImV4cGlyYXRpb25ZZWFyIjoiMjAyMyIsIm51bWJlciI6IjQxMTExMVhYWFhYWDExMTEiLCJleHBpcmF0aW9uTW9udGgiOiIwMiIsInR5cGUiOiIwMDEifSwiaXNzIjoiRmxleC8wOCIsImV4cCI6MTYyMjY2NzM5MywidHlwZSI6Im1mLTAuMTEuMCIsImlhdCI6MTYyMjY2NjQ5MywianRpIjoiMUUwRVRWVktaNjVGMFpBQlZIQ01CRk1RTExWT0wxUE42REdCTkc1UDFEVlNBWDZQQ1ZaSzYwQjdGMDgxQzhBQ
iIsImNvbnRlbnQiOnsicGF5bWVudEluZm9ybWF0aW9uIjp7ImNhcmQiOnsiZXhwaXJhdGlvblllYXIiOn
sidmFsdWUiOiIyMDIzIn0sIm51bWJlciI6eyJtYXNrZWRWYWx1ZSI6IlhYWFhYWFhYWFhYWDExMTEiLCJi
aW4iOiI0MTExMTEifSwic2VjdXJpdHlDb2RlIjp7fSwiZXhwaXJhdGlvbk1vbnRoIjp7InZhbHVlIjoiM
DIifSwidHlwZSI6eyJ2YWx1ZSI6IjAwMSJ9fX19fQ.ZcnMNGM9WbcZeeZ5jQ1E5kVJbeYDZ2hNjkMW5TVM
gXVXKK6Kg6ms9VCQToJ4DUUvT1pk3jGUDNkPMm0zjEYvbiZKa6R1DncKfEUVbWm1pWB1r6KfxlEVqoFHf2
HT3aSrU8qe_ta-fhQtfTC2A8PcqdqsGS9IOGrsXALhaGKbQMc1k4RI2Sa3NXiXv4xHTiLbcLFqGRIMxj1R
ZOhYfNWo3BX3s-6dNAA11oD_S2LkIS9U223K4ibxVK1US62z9yC89gGOY08VmpdVZ8lwESBgQVEd4zir3e
dcSBOvEw55XEWL94E2AbJI7zr0494r7FWIUH02cpEJGWdPF-FUc-h0yA';

String jwtTokenbody = tempJWTToken.split('\\.')[1]; Blob decodedJWTToken = EncodingUtil.base64Decode(jwtTokenbody); Map<String, Object> jwtTokenDataMap = (Map<String, Object>)JSON.deserializeUntyped(decodedJWTToken.toString()); String issData = (String)jwtTokenDataMap.get('iss');
System.debug('___Decode issData' + issData); System.debug('___Decode jwtData' + jwtTokenDataMap);


Output

{content={paymentInformation={card={expirationMonth={value=02}, expirationYear={value=2023}, number={bin=411111, maskedValue=XXXXXXXXXXXX1111}, securityCode={}, type={value=001}}}}, data={expirationMonth=02,
expirationYear=2023, number=411111XXXXXX1111, type=001},
exp=1622667393, iat=1622666493, iss=Flex/08, jti=1E0ETVVKZ65F0ZABVHCMBFMQLLVOL1PN6DGBNG5P1DVSAX6PCVZK60B7F081C8AB,
type=mf-0.11.0}

Reference Links








Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach