📜  在 Passport.js 中禁用会话

📅  最后修改于: 2022-05-13 01:56:34.419000             🧑  作者: Mango

在 Passport.js 中禁用会话

在一个常见的 Web 应用程序中,用于验证用户身份的凭据只会在登录请求期间传输。 Passport 将在成功认证后建立一个持久的登录会话。此会话通过用户浏览器中的 cookie 进行维护。

但是,在某些情况下,不需要会话支持。例如,API 服务器为要验证的每个请求提供所需的凭据。在这种情况下,您可以禁用会话支持。您需要将会话选项设置为 false

app.post('/auth',
  passport.authenticate('local-signin', {
    successRedirect : '/dashboard',
    failureRedirect : '/login',
    session: false
  })
)

或者,可以提供自定义回调以允许应用程序处理成功或失败。

app.get('/auth', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    // your logic to how you serve your user
  })(req, res, next);
});

在上面的例子中, passport.authenticate()是从路由处理程序中调用的,而不是用作路由中间件。这使回调可以访问req 和 res对象以及通过闭包的next方法。

示例:在典型的 Web 应用程序中,用户将在注册后重定向到登录页面。所以,这里我们不需要在新注册后创建会话。让我们看看实现。

项目设置:创建一个新的 NodeJS 项目并将其命名为Auth

mkdir Auth && cd Auth
npm init -y 

安装依赖:

  • 我们可以使用 body-parser 中间件来解析请求体。
    npm i express body-parser
  • 我们可以使用任何模板引擎,在我们的例子中是ejs
    npm i ejs 
  • 我们可以使用uuid 模块创建一个唯一的用户 ID。
    npm i uuid
  • 我们不是直接存储用户输入的密码,而是存储用户密码的哈希值。我们可以使用bcrypt 模块生成密码的哈希值。
    npm i bcrypt
  • 我们需要安装护照模块才能使用它的功能
    npm i passport
  • Passport 提供了很多策略,这里我们将使用passport-local策略。
    npm i passport-local

项目结构:它看起来像这样。

  • passport-config.js:这是护照配置文件。
  • register.ejs:这是注册页面的视图。
  • index.js:这个主服务器设置文件。
register.ejs


    
    
    
    Document
      
    


    
        

GeeksForGeeks

        

Register

           
                                                                                                         
    


passport-config.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const { v4: uuid } = require('uuid')
  
const initialize = (passport, getUserByEmail, save) => {
  
    // Verify callback function implementation
    const register = async (email, password, done) => {
  
        // Check wheather user is already registered or not
        const user = getUserByEmail(email)
  
        // If user is registered, invoke done()
        if (user != null)
            return done(null, user, { 
                message: "You are already registered" })
  
        // Generate user password's hash
        const hashedPassword = await bcrypt.hash(password, 10)
  
        // Create new user 
        const newUser = {
            // Generate user id
            id: uuid(),
            email: email,
            password: hashedPassword
        }
  
        // Save newly created user to database 
        save(newUser)
  
        // Invoke done()
        return done(null, newUser, { 
            message: "Registration Successful" })
    }
  
    // Middleware 
    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    }, register))
}
  
module.exports = initialize


index.js
// Import Modules
const express = require('express')
const bodyParser = require('body-parser')
const passport = require('passport')
const ejs = require('ejs')
  
const intializePassport = require('./config/passport-config')
  
const app = express()
const port = 8080
  
// Dummy in-memory user database
const Users = []
  
// Returns middleware that only parses urlencoded bodies
// A new body object contained pasrse data add to the
// request object 
app.use( bodyParser.urlencoded( { extended: false } ) )
  
// Pass require logic 
intializePassport(
    passport,
    email => Users.find(user => user.email === email),
    user => Users.push(user)
)
  
// Set EJS as view engine
app.set('view engine', 'ejs')
  
// API endpoint
app.get('/', (req, res)=> res.render('register.ejs'))
      
app.post('/register', (req, res, next)=> {
        
        // Invoke implementation of local strategy 
        passport.authenticate('local-signup', 
                     (err, user, info)=>{
  
            // If any error
            if (err)
                res
                    .status(500)
                    .send("

Server Erro!

")             else{                                    // Display the user object                 console.log({                     Error: err,                     User: user,                     Message: info.message                 })                                    // Send message to user                  res.send(`

${ info.message }

`)             }            // Pass req, res and next as closure         })(req, res, next)      })    // Start server app.listen(port, () => console.log(`Server listening on port ${port}!`))



护照-config.js

const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const { v4: uuid } = require('uuid')
  
const initialize = (passport, getUserByEmail, save) => {
  
    // Verify callback function implementation
    const register = async (email, password, done) => {
  
        // Check wheather user is already registered or not
        const user = getUserByEmail(email)
  
        // If user is registered, invoke done()
        if (user != null)
            return done(null, user, { 
                message: "You are already registered" })
  
        // Generate user password's hash
        const hashedPassword = await bcrypt.hash(password, 10)
  
        // Create new user 
        const newUser = {
            // Generate user id
            id: uuid(),
            email: email,
            password: hashedPassword
        }
  
        // Save newly created user to database 
        save(newUser)
  
        // Invoke done()
        return done(null, newUser, { 
            message: "Registration Successful" })
    }
  
    // Middleware 
    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    }, register))
}
  
module.exports = initialize

index.js

// Import Modules
const express = require('express')
const bodyParser = require('body-parser')
const passport = require('passport')
const ejs = require('ejs')
  
const intializePassport = require('./config/passport-config')
  
const app = express()
const port = 8080
  
// Dummy in-memory user database
const Users = []
  
// Returns middleware that only parses urlencoded bodies
// A new body object contained pasrse data add to the
// request object 
app.use( bodyParser.urlencoded( { extended: false } ) )
  
// Pass require logic 
intializePassport(
    passport,
    email => Users.find(user => user.email === email),
    user => Users.push(user)
)
  
// Set EJS as view engine
app.set('view engine', 'ejs')
  
// API endpoint
app.get('/', (req, res)=> res.render('register.ejs'))
      
app.post('/register', (req, res, next)=> {
        
        // Invoke implementation of local strategy 
        passport.authenticate('local-signup', 
                     (err, user, info)=>{
  
            // If any error
            if (err)
                res
                    .status(500)
                    .send("

Server Erro!

")             else{                                    // Display the user object                 console.log({                     Error: err,                     User: user,                     Message: info.message                 })                                    // Send message to user                  res.send(`

${ info.message }

`)             }            // Pass req, res and next as closure         })(req, res, next)      })    // Start server app.listen(port, () => console.log(`Server listening on port ${port}!`))

运行应用程序的步骤:使用以下命令运行 index.js 文件:

node index.js

输出:我们将在终端屏幕上看到以下输出。

Server listening on port 8080

现在打开任何浏览器并转到http://localhost:8080/,我们将看到以下输出:

报名表格

提交表单后,我们将在浏览器上看到注册成功,并在终端屏幕上看到以下输出:

服务器终端