Implementing user authentication in Node.js involves the following key steps:
1. Setting up the Node.js environment and related packages
First, ensure that the Node.js environment is installed. Next, we typically use several packages to facilitate authentication, such as express as the server framework, bcryptjs for password hashing, and jsonwebtoken (JWT) for token generation.
bashnpm init -y npm install express bcryptjs jsonwebtoken
2. Creating the User Model
Use MongoDB and Mongoose to store user data. First, install these packages:
bashnpm install mongoose
Then, define the user model:
javascriptconst mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true } }); const User = mongoose.model('User', UserSchema); module.exports = User;
3. User Registration and Password Hashing
During user registration, the password must be hashed and stored securely. This can be achieved using bcryptjs:
javascriptconst bcrypt = require('bcryptjs'); app.post('/register', async (req, res) => { try { const { username, password } = req.body; const hashedPassword = await bcrypt.hash(password, 10); const newUser = new User({ username, password: hashedPassword }); await newUser.save(); res.status(201).send('User created'); } catch (error) { res.status(500).send(error.message); } });
4. Login and JWT Generation
During user login, validate the username and password, then generate a JWT to send to the client.
javascriptconst jwt = require('jsonwebtoken'); app.post('/login', async (req, res) => { try { const { username, password } = req.body; const user = await User.findOne({ username }); if (!user) { return res.status(404).send('User not found'); } const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return res.status(400).send('Invalid credentials'); } const token = jwt.sign({ id: user._id }, 'secret_key', { expiresIn: '1h' }); res.json({ token }); } catch (error) { res.status(500).send(error.message); } });
5. JWT Authentication Middleware
Create a middleware to verify the JWT, ensuring that only users with valid tokens can access protected routes.
javascriptfunction authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (token == null) return res.sendStatus(401); jwt.verify(token, 'secret_key', (err, user) => { if (err) return res.sendStatus(403); req.user = user; next(); }); } app.get('/protected', authenticateToken, (req, res) => { res.send('Access to protected route'); });
By following these steps, we can build a basic user authentication system in Node.js. This system includes user registration, login, password hashing, and state management using JWT.