MongoDB

Building a Modern Authentication System with JWT

Learn how to implement a secure authentication system using JSON Web Tokens (JWT) in modern web applications.

S

srikanthtelkalapally888@gmail.com

Building a Modern Authentication System with JWT

Authentication is a fundamental part of modern web applications. JSON Web Tokens (JWT) are widely used for secure authentication between clients and servers.

What is JWT?

JWT stands for JSON Web Token. It is a compact and secure way to transmit information between parties.

A JWT contains three parts:

Header.Payload.Signature

JWT Structure

Header

Contains the algorithm and token type.

Example:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains the user information.

Example:

{
  "userId": 1,
  "role": "admin"
}

Signature

Ensures the token has not been modified.

Generating a Token in Node.js

Example using jsonwebtoken:

import jwt from 'jsonwebtoken'

const token = jwt.sign(
  { id: user.id, role: user.role },
  process.env.JWT_SECRET,
  { expiresIn: '15m' }
)

Verifying Tokens

Middleware can verify tokens before allowing access.

const verifyToken = (req, res, next) => {
  const token = req.headers.authorization

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    req.user = decoded
    next()
  } catch (error) {
    res.status(401).json({ message: 'Unauthorized' })
  }
}

Access Token vs Refresh Token

Modern systems use two tokens:

Access Token

  • Short lifespan
  • Used for API requests

Refresh Token

  • Longer lifespan
  • Used to generate new access tokens

Security Best Practices

Important practices include:

  • Use HTTPS
  • Store tokens securely
  • Set token expiration
  • Implement refresh token rotation

Conclusion

JWT provides a secure and scalable way to implement authentication. By combining access tokens, refresh tokens, and proper security practices, developers can build robust authentication systems.

Share this article