PassportJS - 可以在没有数据库的情况下使用本地策略吗?

PassportJS - possible to us local strategy without a database?

我正在构建一个连接到 ElasticSearch 的小型 NodeJS 服务器。我需要用户身份验证,而 elasticsearch 似乎不太适合存储用户信息。

而不是承担额外的开销,例如使用MongoDB 来存储用户帐户,是否可以将 PassportJS 本地策略与 json 用户帐户文件或内存中的用户帐户数组一起使用?

将手动配置用户 - 手动编辑 json 用户文件很容易,而且用户会很少。

编辑 如果可能的话,你能给我举个例子吗?

谢谢

您可以参考这篇优秀的博客 post 来了解 passportJS 身份验证 - Passport authentication。 我还在必要时添加了评论。您只需要将从数据库获取用户数据的逻辑更改为从 JSON 文件获取用户数据的逻辑。

    // config/passport.js

    // load all the things we need
    var LocalStrategy   = require('passport-local').Strategy;

    // load up the users json data
    var User            = require('../app/data/users');

    // expose this function to our app using module.exports
    module.exports = function(passport) {

        // =========================================================================
        // passport session setup ==================================================
        // =========================================================================
        // required for persistent login sessions
        // passport needs ability to serialize and unserialize users out of session

        // used to serialize the user for the session
        passport.serializeUser(function(user, done) {
            done(null, user.id);
        });

        // used to deserialize the user
        passport.deserializeUser(function(id, done) {
            // Write a logic to find this particular user from the json data using userID


            // If not found return done({});

            // else return done(null, userObject);
        });

        // =========================================================================
        // we are using named strategies since we have one for login and one for signup
        // by default, if there was no name, it would just be called 'local'

        passport.use('local-login', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'email',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, email, password, done) { // callback with email and password from our form

            // Write a logic to find this particular user from the json data using email

            // validate for password


            // If not found or password incorrect return done({});

            // else return done(null, userObject);

        }));

    };