In previous blog, we have learnt What is JWT, Anatomy and its authentication flow. Refer here to
In this blog, we will see how a JWT works via an example. We will create JWT for a specific JSON payload and validate its signature.
Step-1
Create a JSON:
Step-2
Create a JWT signing key and decide the signing algorithm:
We can generate a signing key using any secure random source.
- Signing key:
NTNv7j0TuYARvmNMmWXo6fKvM4o6nv/aUi9ryX38ZH+L1bkrnD1ObOQ8JAUmHCBq7Iy7otZcyAagBLHVKvvYaIpmMuxmARQ97jUVG16Jkpkp1wXOPsrF9zwew6TpczyHkHgX5EuLg2MeBuiT/qJACs1J0apruOOJCg/gOtkjB4c=
- Signing algorithm:
HMAC + SHA256
, also known asHS256
.
Creating the “Header”:
Create a Signature:
- Similarly, remove the spaces from the header JSON and base64 encode it
Base64 + HMACSHA256
function on the above concatenated stringJava HMAC SHA256
Dependent on Apache Commons Codec to encode in base64.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class ApiSecurityExample {
public static void main(String[] args) {
try {
String secret = "secret";
String message = "Message";
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
System.out.println(hash);
}
catch (Exception e){
System.out.println("Error");
}
}
}
Create JWT:
Append the generated signature like <header>.<body>.<signature>
Verify JWT:
- Fetches the header part of the JWT (
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
).
{"typ":"JWT","alg":"HS256"}
- Verifies that the
typ
field’s value isJWT
and thealg
isHS256
. It would reject the JWT if fails to verify.
Base64URLSafe(HMACSHA256(...))
If the incoming JWT’s body is different, this step will generate a different signature.
- Checks that the generated signature is the same as the signature from the incoming JWT. If it’s not, then the JWT is rejected.
eyJ1c2VySWQiOiJhYmNkMTIzIiwiZXhwaXJ5IjoxNjQ2NjM1NjExMzAxfQ
) to give us {"userId":"abcd123","expiry":1646635611301}
.expiry
time (since the JWT is expired), JWT is rejected.Pros & Cons of JWT:
- Secure: JWTs are digitally signed using either a secret (HMAC) or a public/private key pair (RSA or ECDSA) which safeguards them from being modified by the client or an attacker.
- Stored only on the client: You generate JWTs on the server and send them to the client. The client then submits the JWT with every request. This saves database space.