Last active
May 28, 2025 14:45
-
-
Save renatoliveira/d5ab7de1095ee44dbe82956b489757e7 to your computer and use it in GitHub Desktop.
JWT Creation and Validation example in Salesforce Apex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // JWT creation and validation example in Apex | |
| String certificateName = 'JWTDemo'; | |
| String audience = 'nova'; | |
| String issuer = 'something'; | |
| String pubKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA26puZ2Bz2py4jJHXsR2bcMeNIFPH+uoXgI3TRMLSAUzWwR3V9Gpy5YFnk6SPJoeiS2IZXpu8+bH+rvwrMgK1vaPBPYlcmNarsmF2MWK41jxpHb2i9VrPcaB6+ckNOcYfdUl9t/BLCXNuuoYx6AIqGylBuZBk3Q/HCDwxtA/Zjze3TrWt40jVNPKEp4t0XwSGg/CXE47qWpzFyXCuE0lEKX8/Kdn7MF1RYbhAKpGLNhpxpnLt89U1IMuqmo2IlC1f404lptYyfyTfWE3SkWX4yONvx1ZMg33QniHpRI4zf+hLKggScOflnxRTh9HC/IHkWC9UvSfkdduiqQpWdzg5YwIDAQAB'; | |
| Blob publicKeyBlob = EncodingUtil.base64Decode(pubKey); | |
| Auth.JWT jwt = new Auth.JWT(); | |
| jwt.setSub(UserInfo.getUsername()); | |
| jwt.setAud(audience); | |
| jwt.setIss(issuer); | |
| Map<String, Object> claims = new Map<String, Object>{ | |
| 'readable_records' => new List<Id>(), | |
| 'editable_records' => new List<Id>() | |
| }; | |
| jwt.setAdditionalClaims(claims); | |
| Auth.JWS jws = new Auth.JWS(jwt, certificateName); | |
| String jwtJsonString = jwt.toJSONString(); | |
| String jwtString = jws.getCompactSerialization(); | |
| // when validate the JWT back: | |
| System.debug(jwtJsonString); | |
| System.debug(jwtString); | |
| // this converts base64Url to base64 | |
| public static String base64UrlToBase64(String base64UrlString) { | |
| String base64 = base64UrlString.replace('-', '+').replace('_', '/'); | |
| while (Math.mod(base64.length(), 4) != 0) { | |
| base64 += '='; | |
| } | |
| return base64; | |
| } | |
| // Split the JWT into parts | |
| List<String> parts = jwtString.split('\\.'); | |
| String encodedHeader = parts[0]; | |
| String encodedPayload = parts[1]; | |
| String encodedSignature = parts[2]; | |
| // Rebuild the signed content | |
| Blob signedContent = Blob.valueOf(encodedHeader + '.' + encodedPayload); | |
| // Decode the signature | |
| Blob signatureBlob = EncodingUtil.base64Decode(base64UrlToBase64(encodedSignature)); | |
| // Verify the signature | |
| Boolean isValid = Crypto.verify( | |
| 'RSA-SHA256', | |
| signedContent, | |
| signatureBlob, | |
| publicKeyBlob // the only thing to retrieve from some custom setting or metadata is the public key to have the blob here | |
| ); | |
| // System.debug('JWT is valid? ' + (isValid ? 'Yes' : 'No')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment