Hapi.js API身份验证

时间:2014-04-08 10:31:03

标签: node.js passport.js passport-local

我正在尝试使用hapi和护照本地策略。首先,我试图让“静态”用户工作,然后我计划将用户信息推送到数据库中。我在下面(以及https://github.com/RyanHirsch/hapi-auth-poc)将按预期验证访问网站的用户,但我无法弄清楚如何正确验证API请求。对于测试,我只是尝试使用cURL发送GET以及用户名/密码而不是成功登录。

我哪里错了?如何使用hapi和passport对API请求进行凭据处理?

var Hapi = require('hapi');
var LocalStrategy = require('passport-local').Strategy;

var config = {
    hostname: 'localhost',
    port: 8000,
    urls: {
        failureRedirect: '/login'
    },
    excludePaths: ['/public/']
};
var plugins = {
    yar: {
        cookieOptions: {
            password: "worldofwalmart",
            isSecure: false
        }
    },
    travelogue: config // use '../../' instead of travelogue if testing this repo locally
}

var server = new Hapi.Server(config.hostname, config.port);
server.pack.require(plugins, function (err) {
    if (err) {
        throw err;
    }
});

server.auth.strategy('passport', 'passport');

var USERS = {
    "van": "walmart"
};

var Passport = server.plugins.travelogue.passport;
Passport.use(new LocalStrategy(function (username, password, done) {

    // Find or create user here...
    // In production, use password hashing like bcrypt
    if (USERS.hasOwnProperty(username) && USERS[username] == password) {
        return done(null, { username: username });
    }

    return done(null, false, { 'message': 'invalid credentials' });
}));
Passport.serializeUser(function (user, done) {

    done(null, user);
});
Passport.deserializeUser(function (obj, done) {

    done(null, obj);
});

// routes
server.route({
    method: 'GET',
    path: '/',
    config: { auth: 'passport' }, // replaces ensureAuthenticated
    handler: function (request, reply) {

        // If logged in already, redirect to /home
        // else to /login
        reply().redirect('/home');
    }
});

server.route({
    method: 'GET',
    path: '/login',
    config: {
        handler: function (request, reply) {
            if (request.session._isAuthenticated()) {
                reply().redirect('/home');
            } else {
                var form = '<form action="/login" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="Log In"/> </div> </form>';
                reply(form);
            }
        }
    }
});


server.route({
    method: 'GET',
    path: '/home',
    config: { auth: 'passport' },
    handler: function (request, reply) {
        // If logged in already, redirect to /home
        // else to /login
        reply("ACCESS GRANTED<br/><br/><a href='/logout'>Logout</a>");
    }
});

server.route({
    method: 'GET',
    path: '/api/home',
    config: {
        validate: {
            payload: {
                username: Hapi.types.String(),
                password: Hapi.types.String()
            }
        },
        auth: false,
        handler: function (request, reply) {
            // If logged in already, redirect to /home
            // else to /login
            Passport.authenticate('local')(request, function (err) {
                console.log("successful authentication?");
                if (err && err.isBoom) {}
                if(request.session._isAuthenticated()) {
                    reply({message: "logged in"});
                }
            });
            // reply({ "working" : "success" });
        }
    }
});

server.start(function () {
    console.log('server started on port: ', server.info.port);
});

1 个答案:

答案 0 :(得分:4)

您尝试使用通过有效负载提供的用户名和密码对您的请求进行身份验证,但已将您的操作配置为使用GET。会发生什么是Hapi忽略了您的参数,因此您的请求失败了。

只需使用POST。

作为旁注,使用这种方法会使你的api依赖于cookie和会话,我更喜欢使用&#34; token&#34;验证并创建无状态服务。我认为护照持有人对你来说是一个不错的选择。