In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Passport for local authentication in Node.js". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Passport for local authentication in Node.js".
I. brief introduction
Passport.js is an authentication middleware designed for Nodejs. Passport-local uses a pass policy to authenticate with a user name and password. This module facilitates authentication using usernames and passwords in nodejs applications.
1.1Setting Node.js
To build the Node.js on Windows, you will need to go to the Node website to download it. Select the installer for your platform (which also includes the NPM package manager) and run the installer to launch the Node.js installation wizard. Follow the wizard steps and click finish when you are finished. If all goes well, you can navigate to the command prompt to verify that the installation was successful, as shown in figure 1.
Figure 1: verification node and npm installation 2. Using Passport for local authentication in Node.js
To set up the application, we need to navigate to the path where the project is located. For programming, I use Visual Studio Code as my preferred IDE. You are free to choose the IDE you like.
2.1 setting implementation
Let's write different documents for actual learning.
2.1.1 setting dependency
Navigate to the project directory and run npm init-y to create the package.json file. This file contains project-related metadata for managing project dependencies, scripts, versions, and so on. Add the following code to the file, where we will specify the required dependencies.
{"name": "passport-app", "version": "1.0.0", "description": "," main ":" server.js "," scripts ": {" start ":" nodemon server.js "}," keywords ": []," author ":"," license ":" ISC "," dependencies ": {" bcrypt ":" ^ 5.0.1 " "ejs": "^ 3.1.6", "express": "^ 4.17.1", "express-flash": "0.0.2", "express-session": "^ 1.17.2", "method-override": "^ 3.0.0", "passport": "^ 0.4.1", "passport-local": "^ 1.0.0"} "devDependencies": {"dotenv": "^ 10.0.0", "nodemon": "^ 2.0.12"}}
To download the dependency, navigate to the directory path that contains the file and use the npm install command. If all goes well, the dependencies will be loaded into the node_modules folder, and you can proceed to further steps.
2.1.2 View-create Welcome screen
Create a folder called views in the root folder and add the following to index.ejs. Exe. This screen will be responsible for displaying the welcome page after successful validation.
Hi Sign Out2.1.3 View-create a login interface
Create a folder called views in the root folder and add the following to login.ejs. Exe. This screen will be responsible for logging in.
Login Email Password LoginSign up2.1.4 View-create Registration screen
Create a folder called views in the root folder and add the following to login.ejs. Exe. This screen will be responsible for registering new users.
Register Name Email Password RegisterLogin2.1.5 creates a pass configuration
In the root folder, add the following to the configuration file. This file will be responsible for configuring the policy with a username and password. The policy also requires a callback, which accepts credentials and calls a done (...) Method to provide user details.
/ / adding passport related configuration const LocalStrategy = require ("passport-local"). Strategy;const bcrypt = require ("bcrypt"); function initialize (passport, getUserByEmail, getUserById) {const authenticateUser = async (email, password, done) = > {const user = getUserByEmail (email); if (user = = null) {return done (null, false, {message: "User not found"}) } try {if (await bcrypt.compare (password, user.password)) {return done (null, user);} else {return done (null, false, {message: "Invalid credentials"});}} catch (e) {return done (e);}}; passport.use (new LocalStrategy ({usernameField: "email"}, authenticateUser)) Passport.serializeUser ((user, done) = > done (null, user.id)); passport.deserializeUser ((id, done) = > {return done (null, getUserById (id));} module.exports = initialize;2.1.6 create controller
In the root folder, add the following to the index file. This file will be responsible for initializing the import, routing, and specifying the pass configuration to validate the request. Remember that .env creates a file in the same location and specifies sensitive information, such as session secrets, application port numbers, and so on.
If (process.env.NODE_ENV! = = "production") {require ("dotenv"). Config ();} / importsconst express = require ("express"); const app = express (); const bcrypt = require ("bcrypt"); const passport = require ("passport"); const flash = require ("express-flash"); const session = require ("express-session"); const methodOverride = require ("method-override"); / / todo-add external db supportconst users = [] / / configuring and initializing passportconst initializePassport = require (". / passport-config"); initializePassport (passport, (email) = > users.find ((user) = > user.email = email), (id) = > users.find ((user) = > user.id = id)); app.set ("view-engine", "ejs"); app.use (express.urlencoded ({extended: false})); app.use (flash ()) App.use (session ({secret: process.env.SESSION_SECRET | | "8unto0n4oc7903zm", resave: false, saveUninitialized: false,})); app.use (passport.initialize ()); app.use (passport.session ()); app.use (methodOverride ("_ method")) / routes / / welcome page// display greetings message for the user and logout buttonapp.get ("/", checkAuthenticated, (req, res) = > {res.render ("index.ejs", {name: req.user.name});}); / / login pageapp.get ("/ login", checkNotAuthenticated, (req, res) = > {res.render ("login.ejs");}) App.post ("/ login", checkNotAuthenticated, passport.authenticate ("local", {successRedirect: "/", failureRedirect: "/ login", failureFlash: true,})); / / new user sign-up pageapp.get ("/ register", checkNotAuthenticated, (req, res) = > {res.render ("register.ejs");}) App.post ("/ register", checkNotAuthenticated, async (req, res) = > {try {const hashedPassword = await bcrypt.hash (req.body.password, 10); users.push ({id: "_" + Math.random (). ToString (36) .slice (2), name: req.body.name, email: req.body.email, password: hashedPassword,}); res.redirect ("/ login") } catch (e) {/ / console.log (e); res.redirect ("/ redirect");} / check if the user is successfully added to array / / console.log (users);}); / / logout of the applicationapp.delete ("/ logout", (req, res) = > {req.logOut (); res.redirect ("/ login");}) / / util methods / / only authenticated user should enter index pagefunction checkAuthenticated (req, res, next) {if (req.isAuthenticated ()) {return next ();} else {res.redirect ("/ login");} / / unauthenticated user should not enter index pagefunction checkNotAuthenticated (req, res, next) {if (req.isAuthenticated ()) {return res.redirect ("/");} next ();} / start serverconst port = process.env.APPLICATION_PORT | | 6001 App.listen (port, () = > {console.log ("Server listening at http://localhost:%s", port);}); 3. Run the application
To run the application, navigate to the project directory and enter the following command, as shown in figure 2. If all goes well, the application will be available from the .env file or 6001.
Figure 2: launch the application thank you for reading, the above is the content of "how to use Passport for local authentication in Node.js". After the study of this article, I believe you have a deeper understanding of how to use Passport for local authentication in Node.js, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.