
{{ $('Map tags to IDs').item.json.title }}
How to Use Passport.js for Authentication
Passport.js is a flexible and comprehensive authentication middleware for Node.js applications. It supports various authentication strategies, allowing developers to integrate different login methods, such as social media logins or local login systems. This tutorial will guide you through the process of setting up Passport.js for authentication in a Node.js application.
Prerequisites
- Basic knowledge of JavaScript and Node.js.
- Node.js installed on your machine.
- Familiarity with Express.js.
1. Setting Up Your Node.js Project
First, create a new directory for your project and navigate into it:
mkdir my-passport-app
cd my-passport-app
npm init -y
Next, install the required dependencies:
npm install express passport passport-local express-session body-parser
2. Creating the Basic Server
Create a file named server.js
in your project directory and set up a basic Express server:
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'your_secret_key', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.send('Welcome to the Passport.js Authentication Example');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
3. Setting Up Passport.js
To integrate Passport into your application, you’ll need to set up a local strategy for handling authentication:
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy((username, password, done) => {
// Replace with your validation logic
if (username === 'admin' && password === 'password') {
return done(null, { username: 'admin' });
}
return done(null, false, { message: 'Invalid credentials' });
}));
passport.serializeUser((user, done) => {
done(null, user.username);
});
passport.deserializeUser((username, done) => {
done(null, { username });
});
4. Creating Login Routes
Add routes for login and logout:
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
5. Creating a Simple Login Form
To allow users to log in, create a simple HTML login form. You can serve it using Express:
app.get('/login', (req, res) => {
res.send(`
<form method="POST" action="/login">
<label>Username:</label>
<input type="text" name="username" required>
<br>
<label>Password:</label>
<input type="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
`);
});
6. Testing the Authentication
Start your server and navigate to http://localhost:3000/login
. Enter the username admin
and password password
(or the credentials you defined). Upon success, you’ll be redirected to the home page.
7. Conclusion
In this tutorial, you’ve set up a basic authentication system using Passport.js with local strategy in an Express application. Continue to explore various authentication strategies offered by Passport, such as OAuth, OpenID, and more, to expand your authentication capabilities!