Token-Based Authentication — Stateless JWT Authentication Patterns
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Token Based Authentication. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Token-based authentication uses signed JWTs for stateless authentication, enabling scalable Distributed Systems without centralized session storage.
// JWT token generation
const jwt = require('jsonwebtoken');
function generateTokens(user) {
const accessToken = jwt.sign(
{
sub: user.id,
role: user.role,
permissions: user.permissions,
tenant_id: user.tenantId
},
process.env.JWT_ACCESS_SECRET,
{ expiresIn: '15m', algorithm: 'RS256' }
);
const refreshToken = crypto.randomBytes(40).toString('hex');
const refreshExpires = Date.now() + 7 * 24 * 60 * 60 * 1000;
// Store refresh token hash
const refreshHash = crypto.createHash('sha256').update(refreshToken).digest('hex');
redis.set(`refresh:${refreshHash}`, user.id, 'PX', 7 * 24 * 60 * 60 * 1000);
return { accessToken, refreshToken, expiresIn: 900 };
}
// Refresh token rotation
app.post('/auth/refresh', async (req, res) => {
const { refreshToken } = req.body;
const hash = crypto.createHash('sha256').update(refreshToken).digest('hex');
const userId = await redis.getdel(`refresh:${hash}`);
if (!userId) return res.status(401).json({ error: 'Invalid refresh token' });
const user = await userService.getById(userId);
const tokens = generateTokens(user);
res.json(tokens);
});
Token-based auth enables stateless APIs where any server can validate requests without shared session state.
← Previous
Session-Based Authentication — Server-Side Session Auth Patterns
Next →
OAuth 2.0 Client Credentials — Service-to-Service Auth with Client Credentials
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro