Home > Web Front-end > JS Tutorial > body text

Securing a Node.js API: A Simple Guide to Authentication

DDD
Release: 2024-09-19 00:29:32
Original
869 people have browsed it

Securing a Node.js API: A Simple Guide to Authentication

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.

1. Basic Authentication

What is it?

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).

How to Implement It

To add Basic Authentication to your API using Express, here’s what you’ll need:

  1. Install the basic-auth package:
   npm install basic-auth
Copy after login
  1. Add the authentication middleware:
   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}`);
   });
Copy after login

Testing It

Use curl to test your Basic Authentication:

curl -u your-username:your-password http://localhost:3000/
Copy after login

Tip: Always use Basic Authentication over HTTPS to ensure credentials are protected.


2. JWT (JSON Web Tokens)

What is it?

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.

How to Implement It

First, install the required packages:

npm install jsonwebtoken express-jwt
Copy after login

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}`);
});
Copy after login

Testing It

First, login to get a token:

curl -X POST http://localhost:3000/login -d '{"username":"user","password":"password"}' -H "Content-Type: application/json"
Copy after login

Then, use the token to access a protected route:

curl -H "Authorization: Bearer <your-token>" http://localhost:3000/protected
Copy after login

JWT is great because the token has an expiration time, and credentials don’t have to be sent with each request.


3. API Key Authentication

What is it?

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.

How to Implement It

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
Copy after login

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}`);
});
Copy after login

Testing It

You can test your API Key authentication with:

curl http://localhost:3000/?api_key=your-api-key
Copy after login

Or using a custom header:

curl -H "x-api-key: your-api-key" http://localhost:3000/
Copy after login

Summary of Authentication Methods

  • Basic Authentication:

    • Pros: Easy to set up.
    • Cons: Credentials are sent with every request, so it should be used over HTTPS.
    • Use case: Simple APIs with a small number of users.
  • JWT Authentication:

    • Pros: Secure, stateless, and scales well.
    • Cons: More complex than Basic Auth.
    • Use case: Scalable APIs that need robust security.
  • API Key Authentication:

    • Pros: Simple and widely used.
    • Cons: API keys are less secure compared to JWT and harder to manage.
    • Use case: Simple APIs where you want to authenticate clients without user management.

Conclusion

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!