JSON Web Token (JWT) is starting to gain traction in the web community as a structured way of transferring objects between two parties in (different) environments. The payload in a JWT is encoded as a JSON object which is signed and/or encrypted. In Userbin we use JWT as container for cookie-stored user sessions.

In this article we present a quick and dirty way to decode a JWT in an Objective-C environment. Note that we don’t handle signature checking or decryption, which is sometimes not needed in a protected environment like a mobile app.

Let’s start by generating a simple JWT in Ruby to demonstrate how native objects are smoothly transferred between different environments. We sign the JWT with a dummy secret since we won’t verify the signature anyway.

We magically move this string into an Objective-C environment.

The encoded JWT consists of three strings (header, payload and signature) concatenated with dots. In this example we don’t care about the header and the signature, so let’s just rip out the middle part:

Now let’s see what’s hiding within the Base64 encoded payload. Before decoding we add a bunch of equal signs that were (possibly) removed during encoding and substitute some characters back to what they used to be.

Peekaboo! A JSON string just waiting to be decoded.

We’ve now transferred data from a native Ruby hash to a native Objective-C NSDictionary. This scenario is very similar to what we do in the Userbin library for iOS where we leave signature verification to the server.