YES I AM THE ONE WHO REQUESTED THE ACCESS
Source: Dev.to
NOTE: This is my first post, so apologies in advance if I’ve misunderstood something. I’m open to discussions and corrections.
What is JWT?
JWT stands for JSON Web Token. It 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.
- JWTs are short‑lived; they expire after a set time.
- Signed tokens verify the integrity of the claims they contain.
- Encrypted tokens hide those claims from other parties.
Use of JWT
Authorization
The most common use case of JWT is authorization—controlling access to routes, services, and resources.
- Authentication → verifies who the user is.
- Authorization → determines what the user is allowed to access.
Information Exchange
JWTs can also be used for secure information exchange between parties. Because they can be signed (e.g., with public/private key pairs), you can be sure the sender is who they claim to be.
Structure of JWT
A JWT consists of three parts, separated by dots (.):
Header
{
"alg": "HS256",
"typ": "JWT"
}
Payload
{
"userId": 123,
"email": "user@example.com",
"role": "admin",
"exp": 1712345678
}
Signature
The signature is created with:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret_key
)
How JWT Authentication Works (Flow)
- User logs in with email & password.
- Server verifies credentials.
- Server generates a JWT using a secret key.
- JWT is sent to the client.
- Client stores the JWT (cookie or
localStorage). - Client includes the JWT in the
Authorizationheader for each request. - Server verifies the JWT and grants access if it is valid.
Advantages of JWT
- Stateless authentication (no DB lookup per request).
- Fast & scalable.
- Easy to use across microservices.
- Works well with REST APIs & mobile apps.
Disadvantages of JWT
- Tokens cannot be revoked easily.
- If a token is stolen, the attacker gains access.
- Payload is readable (not encrypted).
- Large tokens increase request size.
JWT in Express.js
Generate Token
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);
Verify Token (Middleware)
const verifyToken = (req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "No token" });
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) return res.status(403).json({ message: "Invalid token" });
req.user = decoded;
next();
});
};
Final Thoughts
JWT is powerful, fast, and widely adopted—but only when used correctly. Understanding how it works internally helps in designing secure and scalable systems.
I’m starting this as a learning hobby to improve my knowledge and connect with talented people. Feedback and suggestions are always welcome.