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

时间:2016-02-21 11:14:43

标签: node.js express passport.js

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

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

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

修改 如果可能的话,你能指点我一个例子吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以参考这篇优秀的博客文章来了解passportJS身份验证 - Passport authentication。 我还在必要时添加了评论。您只需要将从DB获取用户数据的逻辑更改为从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);

        }));

    };