I built a Node.js API and want to secure it, so I checked the few options I have to choose from. So, I’ll walk you through three common authentication methods: Basic Authentication, JWT (JSON Web Tokens), and API Keys.
Basic Authentication is as simple as it gets. The client sends a username and password with each request in the Authorization header. While it's easy to implement, it’s not the most secure unless you're using HTTPS since the credentials are only base64 encoded (not encrypted).
To add Basic Authentication to your API using Express, here’s what you’ll need:
npm install basic-auth
const express = require('express'); const basicAuth = require('basic-auth'); const app = express(); function auth(req, res, next) { const user = basicAuth(req); const validUser = user && user.name === 'your-username' && user.pass === 'your-password'; if (!validUser) { res.set('WWW-Authenticate', 'Basic realm="example"'); return res.status(401).send('Authentication required.'); } next(); } app.use(auth); app.get('/', (req, res) => { res.send('Hello, authenticated user!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Use curl to test your Basic Authentication:
curl -u your-username:your-password http://localhost:3000/
Tip: Always use Basic Authentication over HTTPS to ensure credentials are protected.
JWT is a more secure and scalable way to authenticate users. Instead of sending credentials with every request, the server generates a token on login. The client includes this token in the Authorization header for subsequent requests.
First, install the required packages:
npm install jsonwebtoken express-jwt
Here’s an example of how you can set up JWT authentication:
const express = require('express'); const jwt = require('jsonwebtoken'); const expressJwt = require('express-jwt'); const app = express(); const secret = 'your-secret-key'; // Middleware to protect routes const jwtMiddleware = expressJwt({ secret, algorithms: ['HS256'] }); app.use(express.json()); // Parse JSON bodies // Login route to generate JWT token app.post('/login', (req, res) => { const { username, password } = req.body; if (username === 'user' && password === 'password') { const token = jwt.sign({ username }, secret, { expiresIn: '1h' }); return res.json({ token }); } return res.status(401).json({ message: 'Invalid credentials' }); }); // Protected route app.get('/protected', jwtMiddleware, (req, res) => { res.send('This is a protected route. You are authenticated!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
First, login to get a token:
curl -X POST http://localhost:3000/login -d '{"username":"user","password":"password"}' -H "Content-Type: application/json"
Then, use the token to access a protected route:
curl -H "Authorization: Bearer <your-token>" http://localhost:3000/protected
JWT is great because the token has an expiration time, and credentials don’t have to be sent with each request.
API Key authentication is simple: you give each client a unique key, and they include it in their requests. It’s easy to implement but not as secure or flexible as JWT, because the same key is reused over and over. In the end is a robust solution, can easily be used to limit the number of api call and many websites are using it. As additional security measures, requests can be limited to a specific ip.
You don’t need any special packages for this, but using dotenv to manage your API keys is a good idea. First, install dotenv:
npm install dotenv
Then, create your API with API Key authentication:
require('dotenv').config(); const express = require('express'); const app = express(); const API_KEY = process.env.API_KEY || 'your-api-key'; function checkApiKey(req, res, next) { const apiKey = req.query.api_key || req.headers['x-api-key']; if (apiKey === API_KEY) { next(); } else { res.status(403).send('Forbidden: Invalid API Key'); } } app.use(checkApiKey); app.get('/', (req, res) => { res.send('Hello, authenticated user with a valid API key!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
You can test your API Key authentication with:
curl http://localhost:3000/?api_key=your-api-key
Or using a custom header:
curl -H "x-api-key: your-api-key" http://localhost:3000/
Basic Authentication:
JWT Authentication:
API Key Authentication:
If you're looking for something quick and easy, Basic Authentication could work, but remember to use HTTPS. If you want more robust, scalable security, go for JWT. For lightweight or internal APIs, API Key authentication might be enough.
Which authentication method are you planning to use or do you have other solutions? Let me know in the comments!
The above is the detailed content of Securing a Node.js API: A Simple Guide to Authentication. For more information, please follow other related articles on the PHP Chinese website!