Lightweight authentication using JWT
Web authentication using Json Web Tokens(JWT) without a database
2 min readAug 20, 2021
JWT stands for JSON Web Token
Concept
JWT uses hashing to verify data.
* token = hash(data) (Also called signature)
* Verification — hash(data) == token
If the data in the token is tampered, the signature of data wont match with the signature of the token. Hence, the token will be invalidated
JWT Token
- Consists of three parts — 1. Header 2.Payload 3. Signature
- Token is dot(.) separated. Contains two dots separating Header, Payload and Signature
- Eg Token — gibberishheader.gibberishpayload.gibberishsignature
- Header contains information about the algorithm that is used to generate the signature. Widely used algorithm is HMACSHA256. Eg.
{
“alg”: “HS256”,
“typ”: “JWT”
}
- Payload contains the data. It can contain the data like emailid, phone number, name etc . Eg.
{
“sub” : “1234567890”,
“name”: “John Doe”,
“exp” : 1516239022
}
- Each key in the payload is called a claim
- Signature = Hash( base64UrlEncode(header) + “.” +
base64UrlEncode(payload), secretkey )
JWT System Design Patterns
- Who generates the secret key
* For sticky sessions, every host can generate its own local secret key.
* Single host applications can generate a key at runtime. Note that, every time the server is restarted, the sessions would be logged out since the key will change and the tokens of existing sessions will be invalidated
* For distributed systems, secret key can be generated from any utility and stored in a centralised secrets keeper like AWS Secrets Manager - Should the tokens be stored in a database
NOOOOOOOO . All the information needed for verification is there in the token. If the payload is tampered, signature verification will fail and the token will be in validated.
Best Practices
- Store the token in cookie and not in sessionStorage or localStorage as it is prone to XSS attacks
- Pass the token with all the API calls
- Validate the subject of the token and expiry with current time
- Reserved Claims — https://auth0.com/docs/tokens/json-web-tokens/json-web-token-claims#reserved-claims