How to decode the JWT token in Apex?

924    Asked by ChristianParsons in Salesforce , Asked on Aug 24, 2023

 Since a JWT token is sent to SFDC and needs to be decoded in Apex class, I tried to decode the JWT token in Apex. But I do not have any idea about how to do that. Can anyone please help me? 

Answered by Aashna Saito

You can consider using EncodingUtil class and base64decode to convert an encrypted string to a Blob for JWT token decode. After the conversion, you can apply toString to turn it into a JSON string. You will also get some JSON methods in Apex to convert a string to an object.


Your Answer

Answer (1)

In Apex, you can decode a JWT (JSON Web Token) using Salesforce's Crypto class and the Blob and EncodingUtil classes. Here's a basic example of how you can decode a JWT token in Apex:

public class JWTDecoder {
    // Method to decode a JWT token
    public static Map decodeJWT(String jwtToken) {
        // Split the token into its three parts: header, payload, and signature
        List jwtParts = jwtToken.split('\.');
        // Decode and parse the payload (second part)
        String payloadJson = jwtParts[1];
        String payloadDecoded = EncodingUtil.base64Decode(payloadJson).toString();
        Map payloadMap = (Map) JSON.deserializeUntyped(payloadDecoded);
        return payloadMap;
    }
}

To use this class, you can simply call the decodeJWT method and pass your JWT token as an argument:

String jwtToken = 'your_jwt_token_here';
Map decodedPayload = JWTDecoder.decodeJWT(jwtToken);
// Access the decoded payload values
String userId = (String) decodedPayload.get('sub');
String username = (String) decodedPayload.get('username');

Keep in mind that this is a basic example, and you might need to handle exceptions, verify the token signature, and perform additional validation depending on your specific requirements and the JWT implementation you're working with. Additionally, ensure that you have the necessary permissions and access controls in place when working with sensitive data in JWT tokens.

6 Months

Interviews

Parent Categories