Home >Web Front-end >JS Tutorial >Local Authentication Using Passport in Node.js

Local Authentication Using Passport in Node.js

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-10 11:15:11725browse

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:

  • Passport.js: A powerful middleware simplifying authentication in Node.js applications. It handles user authentication, allowing access to protected resources.
  • Session-Based Authentication: The server manages authentication state using cookies and server-side sessions. This contrasts with JWT (JSON Web Tokens), where authentication is partially client-side.
  • MongoDB & Mongoose: We'll use MongoDB as our database and Mongoose as its ODM (Object Data Modeling) library for easier interaction.
  • Local Strategy: Passport.js's built-in strategy for username/password authentication.

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:

  1. Create a project directory and initialize a Node.js project:

    <code class="language-bash">mkdir AuthApp
    cd AuthApp
    npm init -y</code>
  2. 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:

  1. Start your MongoDB server.
  2. Run node index.js in your terminal.
  3. Access the application in your browser at 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn