This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.
Last Updated: 2024-11-21
JWT (JSON Web Token) is an alternative to session-based authentication
You take a header like so
{
"alg": "HS256",
"typ": "JWT"
}
and then a payload
{
"name": "John Doe",
"user_id": 1516239022,
"admin": true
}
and a secret (256 bit)
then process is as follows
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
your-256-bit-secret
)
to get a lump of signature:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
In both cases, once the user is authenticated for the first time, the server
sends a seemingly random string to the client, which the client stores in
persistent storage (e.g. web storage, cookies, NSUserDefaults
) and with every
subsequent request, the client will send the string which is used to identify
the user_id on the server.
The best and the worst thing about JWT is that it relies on just one key. If this key is leaked, the whole system is compromised! The only way to recover from this point is to generate a new key pair. This would mean all the current user tokens are invalidated and each user would have to login again.