Passport本地策略和cURL

时间:2014-03-07 14:04:11

标签: node.js curl express git-bash passport.js

我想用CURL测试我的node.js + express + passport.js测试应用程序(RESTful)。我的代码:

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

// Define the strategy to be used by PassportJS
passport.use(new LocalStrategy(
    function(username, password, done) {
        if (username === "admin" && password === "admin") // stupid example
            return done(null, {name: "admin"});

        return done(null, false, { message: 'Incorrect username.' });
    }
));

// Serialized and deserialized methods when got from session
passport.serializeUser(function(user, done) {
    done(null, user);
});

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

// Define a middleware function to be used for every secured routes
var auth = function(req, res, next){
    if (!req.isAuthenticated())
        res.send(401);
    else
        next();
};

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/test', auth, function(req, res){
    res.send([{name: "user1"}, {name: "user2"}]);
});

app.post('/login', passport.authenticate('local'), function(req, res) {
    res.send(req.user);
});

使用curl和

调用/测试
curl "http://localhost:3000/test"

返回“Unauthorized”(到目前为止这是正确的)。

使用curl和

调用/登录(POST)
curl --data "username=admin&password=admin" http://localhost:3000/login

的工作原理。但在下次请求时,我的登录信息被“遗忘”了。 这是因为curl无法处理会话吗?有没有解决方法? 我的程序对于RESTful应用程序是否正确?

1 个答案:

答案 0 :(得分:12)

首先,当您使用

登录时,使curl保存Cookie
curl --cookie-jar jarfile --data "username=admin&password=admin" http://localhost:3000/login

访问/test时读取存储的Cookie:

curl --cookie jarfile "http://localhost:3000/test"

在使用Node.js v0.10.26和Express 3.5.0在我的机器(Ubuntu 12.04)上运行之前,需要对应用程序本身进行一些修改。我使用express --sessions nodetest生成了一个新的Express应用,并在app.js中编辑了代码,如下所示。一旦我安装了依赖项,我运行了应用程序并使用curl命令。

app.js

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var app = express();

// Define the strategy to be used by PassportJS
passport.use(new LocalStrategy(
    function(username, password, done) {
        if (username === "admin" && password === "admin") // stupid example
            return done(null, {name: "admin"});

        return done(null, false, { message: 'Incorrect username.' });
    }
));

// Serialized and deserialized methods when got from session
passport.serializeUser(function(user, done) {
    done(null, user);
});

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

// Define a middleware function to be used for every secured routes
var auth = function(req, res, next){
    if (!req.isAuthenticated())
        res.send(401);
    else
        next();
};

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/test', auth, function(req, res){
    res.send([{name: "user1"}, {name: "user2"}]);
});

app.post('/login', passport.authenticate('local'), function(req, res) {
    res.send(req.user);
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

卷曲脚本

#!/bin/sh
# curl-login.sh
rm jarfile
echo --- login
curl --cookie-jar jarfile --data "username=admin&password=admin" http://localhost:3000/login
echo --- test
curl --cookie jarfile "http://localhost:3000/test"

带卷曲输出的控制台日志

$ node app &
$ sh curl-login.sh
--- login
POST /login 200 2ms - 21b
{
  "name": "admin"
}--- test
GET /test 200 1ms - 60b
[
  {
    "name": "user1"
  },
  {
    "name": "user2"
  }
]

请注意

的使用
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.js中的

。如果没有以上两行,会话就不会

您的问题中的代码也缺少创建HTTP服务器的部分,但我认为这只是一个复制粘贴问题;我指的是

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});