How to decode JWT and validate the signature in Swift?
JSON Web Tokens are commonly used in web&mobile applications for authentication or licensing a product or other purposes. There are some JWT public libraries that can be found on GitHub. But if you want to just decode a JWT, it is not hard to implement it without a third-party library with CryptoKit framework which is available with iOS 13.
Let’s start with decoding JWT which consists of 3 sections: header, payload, and signature (header.payload.signature)
Let’s create a JWT with RSA 256 method in the jwt.io website as seen below.
We can split JWT by “.” to get three parts.
If we want to see the payload in JSON format, we need to convert it back from the base64 encoded format. We should not miss the padding part. For more information about padding in cryptography, you can visit the wiki.
It’s so easy to decode the JWT header and payload section. What about the signature part? How can we validate it? As you can see in the above image-1, signed data is consists of encoded {header}.{payload} text.
We will validate the signed data with the public key by using the CryptoKit framework. We need ‘public key’, ‘signed’, and ‘signature’ data to do it.
We will use ‘SecKeyVerifySignature’ method to verify signature.
func SecKeyVerifySignature(_ key: SecKey,
_ algorithm: SecKeyAlgorithm,
_ signedData: CFData,
_ signature: CFData,
_ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool
1 — Create a ‘SecKey’ instance from our public key data.
2 — Define the algorithm
3 — Call the method
I tried to show a simple JWT decode and verification process with Swift in iOS 13 and above. You can check with invalid data and will get ‘false’ verification. You can also use the same functions for Objective-C language. I created some sample codes for Objective-C here: https://gist.github.com/tnrvrd/2823cdaeada30a74987b8292cf9cb552
Hope it’s helpful for you!
You can give this post claps 👏 and follow if you enjoyed reading and want to read and learn more.
Thank you for reading.