Using Passport.js for Authentication in Node.js
Learn how to use Passport.js for authentication in Node.js, and understand the basics of authentication and authorization.
Introduction to Passport.js
Passport.js is a popular authentication middleware for Node.js that provides a comprehensive set of strategies for authenticating with various sources, such as databases, social media platforms, and more. To use Passport.js with Node.js, you need to install the passport package. Run the following command in your terminal:
npm install passport
Step 1: Create a New Node.js Project
Create a new directory for your project and navigate to it in your terminal. Then, run the following command to create a new npm project:
npm init -y
Step 2: Install Required Packages
Install the required packages:
npm install express passport
Step 3: Create a New Express App
Create a new file called app.js and add the following code to it:
const express = require('express');
const app = express();
const passport = require('passport');
app.use(express.static('public'));
app.use(passport.initialize());
app.use(passport.session());
const users = [
{ id: 1, username: 'john', password: 'hello' },
{ id: 2, username: 'jane', password: 'world' }
];
passport.use(new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password'
},
(username, password, done) => {
const user = users.find((user) => user.username === username);
if (!user) {
return done(null, false, { message: 'Invalid username or password' });
}
if (user.password !== password) {
return done(null, false, { message: 'Invalid username or password' });
}
return done(null, user);
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
const user = users.find((user) => user.id === id);
done(null, user);
});
app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), (req, res) => {
res.redirect('/');
});
app.get('/login', (req, res) => {
res.sendFile(__dirname + '/login.html');
});
Step 4: Create a New HTML File
Create a new HTML file called login.html in the public directory:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username...">
<input type="password" name="password" placeholder="Password...">
<button type="submit">Login</button>
</form>
</body>
</html>
You can now start the server by running the following command in your terminal:
node app.js
Open a web browser and navigate to http://localhost:3000/login to test the login page.