Explain authentication vs authorization. How would you implement JWT-based authentication?

⚙️ Backend Development9/21/2025
Understanding the difference between authentication and authorization, and implementing secure JWT-based authentication systems.

Authentication vs Authorization

Authentication ("Who are you?")

  • Definition: Verifying the identity of a user
  • Process: Login with credentials (username/password, OAuth, biometrics)
  • Result: Confirm user identity
  • Example: Entering password to access email

Authorization ("What can you do?")

  • Definition: Determining what an authenticated user can access
  • Process: Check permissions and roles
  • Result: Grant or deny access to resources
  • Example: Admin can delete posts, regular user cannot

JWT (JSON Web Token)

Structure

header.payload.signature

Header:

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

Payload:

{
  "sub": "user123",
  "name": "John Doe",
  "role": "admin",
  "iat": 1516239022,
  "exp": 1516242622
}

Implementation Example

Login Endpoint

app.post('/login', async (req, res) => {
    const { email, password } = req.body;
    
    // Authenticate user
    const user = await User.findOne({ email });
    if (!user || !await bcrypt.compare(password, user.password)) {
        return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // Generate JWT
    const token = jwt.sign(
        { 
            userId: user.id, 
            email: user.email, 
            role: user.role 
        },
        process.env.JWT_SECRET,
        { expiresIn: '24h' }
    );
    
    res.json({ token, user: { id: user.id, email: user.email } });
});

Middleware for Protection

function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    
    if (!token) {
        return res.status(401).json({ error: 'Access token required' });
    }
    
    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
        if (err) {
            return res.status(403).json({ error: 'Invalid token' });
        }
        req.user = user;
        next();
    });
}

Authorization Middleware

function authorize(roles) {
    return (req, res, next) => {
        if (!roles.includes(req.user.role)) {
            return res.status(403).json({ error: 'Insufficient permissions' });
        }
        next();
    };
}

// Usage
app.delete('/users/:id', authenticateToken, authorize(['admin']), deleteUser);

Security Best Practices

  1. Secret Management: Use strong, randomly generated secrets
  2. Token Expiration: Short-lived access tokens
  3. Refresh Tokens: For long-term access
  4. HTTPS Only: Never send tokens over HTTP
  5. Secure Storage: HttpOnly cookies for web apps
  6. Logout: Token blacklisting or short expiry
By: System Admin