DEV Community

Suhas Palani
Suhas Palani

Posted on

Authentication & Authorization

  • Topic: "Implementing Authentication with JWT"
  • Description: How to implement authentication and authorization using JSON Web Tokens (JWT).

Content:

1. Introduction to JWT

  • What is JWT: Explain JSON Web Tokens and their structure.
  • Why JWT: Discuss the benefits of using JWT for authentication.

2. Setting Up JWT

  • Install Dependencies:

    npm install jsonwebtoken bcryptjs
    
  • Configure JWT:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const secret = 'your_jwt_secret'; // Use an environment variable in real applications
```
Enter fullscreen mode Exit fullscreen mode

3. User Model and Registration

  • Define User Schema:

    const userSchema = new mongoose.Schema({
      username: { type: String, required: true, unique: true },
      password: { type: String, required: true }
    });
    
    userSchema.pre('save', async function(next) {
      if (this.isModified('password')) {
        this.password = await bcrypt.hash(this.password, 10);
      }
      next();
    });
    
    const User = mongoose.model('User', userSchema);
    
  • User Registration Endpoint:

    app.post('/register', async (req, res) => {
      const user = new User(req.body);
      try {
        await user.save();
        res.status(201).json(user);
      } catch (err) {
        res.status(400).json({ error: err.message });
      }
    });
    

4. User Login and Token Generation

  • Login Endpoint:

    app.post('/login', async (req, res) => {
      const { username, password } = req.body;
      try {
        const user = await User.findOne({ username });
        if (user && await bcrypt.compare(password, user.password)) {
          const token = jwt.sign({ id: user._id, username: user.username }, secret, { expiresIn: '1h' });
          res.json({ token });
        } else {
          res.status(401).send('Invalid credentials');
        }
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    

5. Protecting Routes with Middleware

  • Authentication Middleware:

    const authMiddleware = (req, res, next) => {
      const token = req.header('Authorization').replace('Bearer ', '');
      if (!token) {
        return res.status(401).send('Access denied');
      }
      try {
        const decoded = jwt.verify(token, secret);
        req.user = decoded;
        next();
      } catch (err) {
        res.status(400).send('Invalid token');
      }
    };
    
  • Protecting an Endpoint:

    app.get('/profile', authMiddleware, async (req, res) => {
      try {
        const user = await User.findById(req.user.id);
        res.json(user);
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    

6. Testing Authentication

  • Using Postman: Demonstrate how to register a user, log in to receive a JWT, and use the JWT to access protected routes.
  • Example Workflow:
    1. Register a new user at /register.
    2. Log in with the new user at /login to get a token.
    3. Access the protected /profile route using the token in the Authorization header.

This detailed breakdown for weeks 7 to 10 includes explanations and hands-on code examples to provide a comprehensive learning experience.

Top comments (0)