How to implement JSON Web Token (JWT) authentication in Node.js



Image not found!!

JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. JWTs can be used for authentication and authorization purposes in web applications. In a Node.js application, you can implement JWT authentication using libraries like jsonwebtoken and express. Here's a step-by-step guide:

  1. Install Dependencies: Install the necessary npm packages using the following commands:

    bash
    npm install express jsonwebtoken
  2. Create an Express Application: Create a new file (e.g., app.js), and set up a basic Express application.

    javascript
    const express = require('express'); const app = express(); const port = 3000; app.use(express.json()); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
  3. Generate JWT Tokens: Create a utility function to generate and sign JWT tokens. You can use the jsonwebtoken library for this purpose.

    javascript
    const jwt = require('jsonwebtoken'); function generateToken(user) { const payload = { userId: user.id, username: user.username, }; const options = { expiresIn: '1h', // Token expiration time }; return jwt.sign(payload, 'your-secret-key', options); }
  4. Implement User Authentication: Create a route for user authentication. For simplicity, let's assume you have a hardcoded user object.

    javascript
    const users = [ { id: 1, username: 'john', password: 'password123' }, ]; app.post('/login', (req, res) => { const { username, password } = req.body; const user = users.find((u) => u.username === username && u.password === password); if (user) { const token = generateToken(user); res.json({ token }); } else { res.status(401).json({ message: 'Invalid credentials' }); } });
  5. Protect Routes with JWT: Create a middleware to protect routes that require authentication. This middleware verifies the JWT token.

    javascript
    function authenticateToken(req, res, next) { const token = req.header('Authorization'); if (!token) { return res.status(401).json({ message: 'Unauthorized' }); } jwt.verify(token, 'your-secret-key', (err, user) => { if (err) { return res.status(403).json({ message: 'Forbidden' }); } req.user = user; next(); }); }
  6. Use JWT Middleware: Apply the authenticateToken middleware to the routes that require authentication.

    javascript
    app.get('/protected-route', authenticateToken, (req, res) => { res.json({ message: 'This is a protected route', user: req.user }); });

Now, when a user successfully logs in and receives a JWT token, they can use that token to access protected routes. The authenticateToken middleware will verify the token before granting access to the protected resource.