API Authentication: JWT, OAuth, and API Keys Deep Dive

Every API Needs Authentication

Without authentication, anyone can access any data. The question is not whether to implement auth, but which mechanism fits your use case.

API Keys: Simplest Approach

# Include in header
GET /api/data HTTP/1.1
Authorization: Bearer sk_live_abc123xyz

# Python validation
def require_api_key(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        key = request.headers.get("Authorization", "").replace("Bearer ", "")
        if not is_valid_key(key):
            return jsonify({"error": "Invalid API key"}), 401
        return f(*args, **kwargs)
    return decorated

JWT (JSON Web Tokens)

const jwt = require("jsonwebtoken");

// Generate token on login
app.post("/login", async (req, res) => {
    const user = await db.users.findByEmail(req.body.email);
    if (!user) return res.status(401).json({ error: "Invalid" });
    
    const token = jwt.sign(
        { userId: user.id, role: user.role },
        process.env.JWT_SECRET,
        { expiresIn: "24h" }
    );
    res.json({ token });
});

// Verify on protected routes
const authenticate = (req, res, next) => {
    const token = req.headers.authorization?.split(" ")[1];
    try {
        req.user = jwt.verify(token, process.env.JWT_SECRET);
        next();
    } catch (err) {
        res.status(401).json({ error: "Invalid token" });
    }
};

OAuth 2.0: Third-Party Login

Login with Google/GitHub/Facebook – that is OAuth. You delegate authentication to a trusted provider.

Comparison

Method Best For Complexity
API Keys Server-to-server Low
JWT User auth, stateless apps Medium
OAuth 2.0 Third-party login High
Session Cookies Traditional web apps Medium

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top