JSON Web Tokens (JWT): The Key to Stateless Authentication(part5)
Hey guys! Like I said, we’re gonna dig into JSON Web Tokens, or JWT for short. This stuff’s pretty big in how websites do login stuff these days so let’s break it down!
What’s JWT?
JWT is this open standard (RFC 7519) that shows how to pack and send info between different parts as a JSON object. To make it simple, it’s a safe way to wrap up and send data that others can check and trust.
How JWT is built?
A JWT has three parts, with dots (.) between them:
- Header
- Payload
- Signature
header.payload.signature
It looks kinda like this: xxxxx.yyyyy.zzzzz
Let’s look at each part:
- Header: Has info about the token the kind of token (JWT) and the method used to make it secure (like HMAC, SHA256, RSA, HS256 or RS256.).
- Payload: Holds claims, which are facts about the user and any extra details(like user role…)
- Signature: Makes sure no one has messed with the token. It’s made by mixing the coded header coded payload, and a secret key.
JWTs aren’t meant to keep things secret. They’re used to make sure the data is real. People sign and encode JWTs, but they don’t encrypt them.
How JWT Does Its Thing
- You log in with your username and password
- The server checks if you’re legit and makes a JWT
- The server sends the JWT back to you
- You keep the JWT safe (in your browser’s local storage)
- You send the JWT with every request you make after that
- The server double-checks the JWT and gives you the info you asked for
Benefits of JWT:
- No state: The server doesn’t have to keep track of session info
- Easy to grow: Great for spread-out systems and tiny services
- Works on phones: Good on different platforms
- Quick: Cuts down on checking the database for login stuff
Possible Downsides
- Big tokens: JWTs can take up more space than normal session tokens
- Can’t take back: Once you give out a JWT, it stays good until it runs out
- Safety issues if you don’t set it up right
Things to Do
- Don’t spill the beans: Never put private stuff in the payload
- Keep it quick: Use short expiration times(or otherwise others would authorize themselves as you or one of the users)
- Stick to HTTPS: Always send JWTs through HTTPS
- Check everything: Don’t just trust the payload
How a JWT Works in Real Life
Let’s say we’re making a basic app for jotting down notes. Here’s how we might use JWT:
User logs in:
// Server-side code (Node.js with Express)
app.post('/login', (req, res) => {
// Verify user credentials
const user = authenticateUser(req.body);
if (user) {
const payload = { userId: user.id, username: user.username };
const token = jwt.sign(payload, 'your-secret-key', { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
User makes a request with the JWT:
// Client-side code
fetch('https://api.example.com/notes', {
headers: {
'Authorization': 'Bearer ' + jwtToken
}
})
.then(response => response.json())
.then(data => console.log(data));
Server verifies the JWT:
// Server-side middleware
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'your-secret-key', (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
Here’s a practical application will help you understand how JWT works in a real-world scenario, including token generation, verification, and using it to protect routes. As you build this, you’ll see firsthand how JWT enables stateless authentication in a web application.
Why Use JWT?
One of the best things about using JWT is how it lets you log in smoothly across different services without having to sign in over and over. Here’s why this is so cool:
Think about building a bunch of money-related services — a bank app, a tool to plan for retirement, and a platform for investing. With JWT, you can make logging in the same across all these services. By sharing the same secret key between your bank server, retirement server, cryptocurrency server, and investment server, someone can log in once and get into all the platforms. This works because all the servers can spot and check the JWT token.
JWT still works great even when you’ve got a bunch of servers sharing the work. Each server can check the token on its own without asking some central database. This makes things faster and lets you grow your system easier. It doesn’t matter which server gets a user’s request — they’ll still be logged in.
This setup makes things way better for people using your stuff. They can hop between different parts — like checking how much money they have then looking at their retirement stuff, and buying some stocks — without having to log in over and over. It’s kind of like having one key that opens all the doors in your money world.
This method works well for microservices setups. Every microservice can check who the user is and what they’re allowed to do without having to talk to a main authentication service each time. This cuts down on network traffic and spots where things could go wrong making the system stronger and quicker to respond.
Keep in mind, with more power comes more duty. While JWT makes this smooth experience possible, it’s super important to put in place good security steps. These include making tokens expire and storing them to protect your users’ info and access.
Don’t forget, JWTs are cool, but they’re not perfect for everything. They work great in some situations, but old-school server sessions might be better in others. Always think about what you need when picking how to do authentication.
In our next article, we’ll check out how JWTs fit in with other web security stuff, and how they work with other things we’ve talked about, like OAuth and 2FA.
Keep writing code, stay safe online, and we’ll see you next time!