Home >Web Front-end >JS Tutorial >Local Authentication Using Passport in Node.js
This tutorial demonstrates building a secure Node.js web application with local authentication using Passport.js and a MongoDB database. We'll focus on session-based authentication, a robust approach leveraging server-side session management and cookies.
Key Concepts:
Prerequisites:
Ensure you have Node.js and MongoDB installed. Instructions for installing these can be found on their respective websites. Familiarity with Node.js, Express.js, and basic MongoDB concepts is helpful.
Project Setup:
Create a project directory and initialize a Node.js project:
<code class="language-bash">mkdir AuthApp cd AuthApp npm init -y</code>
Install necessary packages:
<code class="language-bash">npm install express body-parser express-session passport passport-local-mongoose mongoose connect-ensure-login</code>
Server-Side Code (index.js
):
<code class="language-javascript">const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const expressSession = require('express-session')({ secret: 'your-secret-key', resave: false, saveUninitialized: false }); const passport = require('passport'); const mongoose = require('mongoose'); const passportLocalMongoose = require('passport-local-mongoose'); const connectEnsureLogin = require('connect-ensure-login'); // MongoDB Connection mongoose.connect('mongodb://localhost/MyDatabase', { useNewUrlParser: true, useUnifiedTopology: true }); // User Schema const userSchema = new mongoose.Schema({ username: String }); userSchema.plugin(passportLocalMongoose); const User = mongoose.model('User', userSchema); // Passport Configuration passport.use(User.createStrategy()); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); // Middleware app.use(express.static(__dirname)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressSession); app.use(passport.initialize()); app.use(passport.session()); // Routes app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login?info=Invalid credentials' })); app.get('/login', (req, res) => res.sendFile('html/login.html', { root: __dirname })); app.get('/', connectEnsureLogin.ensureLoggedIn(), (req, res) => res.sendFile('html/index.html', { root: __dirname })); app.get('/private', connectEnsureLogin.ensureLoggedIn(), (req, res) => res.sendFile('html/private.html', { root: __dirname })); app.get('/user', connectEnsureLogin.ensureLoggedIn(), (req, res) => res.json({ user: req.user })); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`App listening on port ${port}`)); //Register Sample Users (remove or comment out after initial setup) User.register({username: 'testuser'}, 'password', (err, user) => { if (err) console.error(err); });</code>
Client-Side Code (HTML & CSS):
Create html
and css
folders in your project root. Populate them with the necessary HTML files (index.html
, login.html
, private.html
) and a styles.css
file for styling (refer to the original response for example code). The client-side JavaScript will need to be adjusted slightly to match the updated server-side routes and responses.
Running the Application:
node index.js
in your terminal.http://localhost:3000
.This revised response provides a more concise and streamlined implementation, focusing on the core aspects of local authentication with Passport.js. Remember to replace "your-secret-key"
with a strong, randomly generated secret. The sample user registration should be removed or commented out after initial setup for security. Error handling and more robust features can be added as needed.
The above is the detailed content of Local Authentication Using Passport in Node.js. For more information, please follow other related articles on the PHP Chinese website!