JSON web token - JWT
When sending data from an application to a backend server you can use json web token (JWT) to make sure the data has not been tampered with. The token is compact making it quick to send to the backend.
Here is an example of a token:
A token is separated into three parts; Header, payload and signature. And, as you can see in the example above, these parts are separated by a “.” All three parts are base64 encoded. Let’s go trough what the different parts contains.
Part 1 - Introduction
The header mostly consists of two parts alg, and typ.
Alg defines what hashing algoritm has been used to create the signature(which we will look at soon). And typ defines type of token, which is JWT.
The payload contains the data that you want to send to your backend. Example:
The signature consists of a base64 encoded HS256-hash built on the first two parts of the token. And this is signed with a shared secret that the app and the backend has.
Part 2 - Example: Creating a JWT with PHP
Line 3: This line base64 encodes the header json.
Line 4: This line base64 encodes the payload json.
Line 6: Here the the base64 strings are concatenated to one that looks like this:
Line 10: Here the signature is created. It creates a hash with the s256 algoritm with the secret key that you can see on line 8. This is string is also base64 encoded.
Line 12: This line concatenates the signature with the rest of the values, and creating a jwt token looking like this:
Part 3: Example: Verifying signature
This code checks so that the signature that was received checks out.
Line 2: $recieved_jwt contains the jwt. This would be received from a $_POST value in real life.
Line 5: $jwt_values is an array with the jwt values in it.
Line 7: $recieved_signature contains the signature from the original jwt
Line 8: we separate the header and payload an concatenates them.
Line 10: We create a new signature with the new header and payload.
Line 12: Check if the signature we created is the same as the one we received. If it is the data has not been tampered with.
Part 4 - A quick checklist
- Base64 encode a header JSON Object.
- Base64 encode a payload JSON Object.
- Concatenate the header and payload strings with “.” separator
- Compute the signature of the header and payload.
- Base64 encode the signature.
- Concatenate the signature to the header and payload string.
A json web token is quite easy to create yourself. And it’s easy to validate the signature as well. If the shared key (or $secret_key as its called above) gets in the wrong hands you can not trust the signatures anymore and need to change it.