JWT
What is JWT
JWT defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
- This information can be verified and trusted because it is digitally signed.
Nothing is stored on server, JWT itself has all the data it needs
- Client/browser manages the session
const JWT = require("jsonwebtoken"); const bcrypt = require("bcryptjs"); const createToken = (userInfo) => JWT.sign({ sub: userInfo.id, email: userInfo.email }, process.env.SECRET); const verifyPassword = (attemptedPw, hashedPw) => bcrypt.compareSync(attemptedPw, hashedPw); const hashPassword = (password) => bcrypt.hashSync(password); const verifyToken = (token) => JWT.verify(token, process.env.SECRET); module.exports = { createToken, verifyPassword, hashPassword, verifyToken };
Common use cases
See "Detailed Use Cases" section below on security concerns
Authorization
JWT is a signed secret key used for authorization
- Used for things like session cookie
Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
Information Exchange
JSON Web Tokens are a good way of securely transmitting information between parties.
Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are.
Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
Signed Token
Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties.
When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
JWT Structure
JWT has three parts:
- Header (algo/token type)
- Payload (sub/name/iat)
- Signature
- Holds encoded version of the data
- hashed header + data + secret key should be equal to this portion of the JWT
- This is how we ensure that the data was not manipulated by an attacker
- hashed header + data + secret key should be equal to this portion of the JWT
- Holds encoded version of the data
They are separated by the dots (.
)
<header_hash>.<payload_hash>.<signature_hash>
Each individual parts are ran through base64
encoding to form each part.
Header
Header usually contains two parts:
- Type of token
- usually
JWT
- usually
- Signing algorithm being used
- such as
HMAC SHA256
orRSA
- such as
{ "alg": "HS256", "typ": "JWT" }
Then, this JSON is Base64Url
encoded to form the first part of the JWT.
Payload
Payload contains claims
.
Claims
are statements about an entity (typically, the user) and additional data. There are three types of claims:registered
,public
, andprivate
claims.
Registered Claims
These are a set of predefined claims
which are not mandatory but recommended, to provide a set of useful, interoperable claims.
- Some of them are:
iss
(issuer),exp
(expiration time),sub
(subject),aud
(audience), and others.Sub
can be id of the userIAT
= issued at time = expiration- Security reason
- If someone gets a hold of JWT token of a user without expiration, they can act as the user indefinitely
- Can also be called other things like
EAF
- Security reason
Public Claims
These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.
Private Claims
These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.
Illustration of Payload
{ "sub": "1234567890", "name": "John Doe", "admin": true }
Security of Payload
For signed tokens, this information, though protected against tampering, is readable
by anyone.
Do NOT put secret information in the payload
or header
elements of a JWT unless it is encrypted
.
Signature
Exposure of secret key will compromise the data
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), <256-bit-secret>)
The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.
Detailed Use Cases
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned.
Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header
using the Bearer schema:
Authorization: Bearer <token>
Note that if you send JWT
tokens through HTTP headers
, you should try to prevent them from getting too big.
- Some servers don't accept more than
8 KB
in headers.
If the token is sent in the Authorization header, Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies.
Security Concerns
DO NOT store JWT
or any authentication or authorization in local storage
.
- Do not store session identifiers in
local storage
as the data is always accessible byJavaScript
Cookies
can mitigate this risk using thehttpOnly
flag.
Due to the browser's security guarantees it is appropriate to use local storage
where access to the data is not assuming authentication
or authorization
.
- A single Cross Site Scripting can be used to steal all the data in these objects, so again it's recommended not to store sensitive information in
local storage
. - Use the object
sessionStorage
instead oflocalStorage
if persistent storage is not needed. sessionStorage
object is available only to that window/tab until the window is closed.
A single Cross Site Scripting
can be used to load malicious data into these objects too, so don't consider objects in these to be trusted.
vs SAML
As JSON
is less verbose than XML
, when it is encoded its size is also smaller, making JWT
more compact than SAML
.
This makes JWT
a good choice to be passed in HTML
and HTTP
environments.