User authentication is a fundamental aspect of web application development. It’s the process of verifying the identity of users accessing your application and ensuring that they have the appropriate permissions to perform specific actions. In this article, we’ll explore how to implement user authentication in Express.js, a popular web application framework for Node.js.
Prerequisites
Before we dive into implementing user authentication, you should have a basic understanding of the following technologies:
- Node.js: Ensure that you have Node.js installed on your system.
- Express.js: Familiarity with the Express.js framework is essential for this implementation.
- MongoDB: We’ll use MongoDB as our database, so you should be comfortable with MongoDB and Mongoose, a popular ODM (Object Data Modeling) library for MongoDB.
- Basic knowledge of HTTP: Understanding how HTTP requests and responses work will be helpful.
Setting up the Project
To get started, create a new Express.js project and install the necessary dependencies. You can use the following commands to initialize your project:
mkdir express-authentication
cd express-authentication
npm init -y
npm install express mongoose express-session passport passport-local
- express is the core library for building the web application.
- mongoose is used to connect to the MongoDB database.
- express-session is a middleware for managing user sessions.
- passport is a popular authentication middleware for Node.js.
- passport-local is a Passport strategy for authenticating with a username and password.
Configuring Your Application
- Create an Express application:
const express = require('express');
const app = express();
- Set up your MongoDB connection using Mongoose:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true });
- Configure Express to use relevant middleware. In particular, we’ll use
express-session
andpassport
:
const session = require('express-session');
const passport = require('passport');
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
- Define a user model using Mongoose. This model will represent the user entity in your database:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
password: String
});
const User = mongoose.model('User', userSchema);
Implementing User Registration
Now, let’s implement user registration:
- Create a registration route that renders a registration form:
app.get('/register', (req, res) => {
res.render('register.ejs');
});
- Handle the form submission:
app.post('/register', (req, res) => {
const newUser = new User({ username: req.body.username });
User.register(newUser, req.body.password, (err, user) => {
if (err) {
console.log(err);
return res.render('register.ejs');
}
passport.authenticate('local')(req, res, () => {
res.redirect('/dashboard');
});
});
});
- Create a registration form in a view (e.g.,
register.ejs
):
<form method="post" action="/register">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Register</button>
</form>
Implementing User Login
Next, let’s implement user login:
- Create a login route that renders a login form:
app.get('/login', (req, res) => {
res.render('login.ejs');
});
- Handle the login form submission using Passport:
app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login'
}), (req, res) => {});
- Create a login form in a view (e.g.,
login.ejs
):
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Log In</button>
</form>
Implementing User Logout
To log out a user, create a logout route:
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
Protecting Routes
You may want to protect certain routes from unauthenticated access. To do this, use the ensureAuthenticated
function:
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
app.get('/dashboard', ensureAuthenticated, (req, res) => {
res.render('dashboard.ejs');
});
Conclusion
In this article, we’ve covered the basics of implementing user authentication in an Express.js application using Passport for authentication and MongoDB for storing user data. By following these steps, you can create a secure and functional authentication system for your web application. Remember to keep your users’ information safe, use encryption for storing passwords, and consider additional security measures for a production-ready application. User authentication is a critical component of building web applications that protect sensitive user data and provide personalized experiences.
Leave a Reply