我想使用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 调用 /test 接口
curl "http://localhost:3000/test"
返回"未授权"(到这里是正确的)。
使用curl调用/login (POST)并
curl --data "username=admin&password=admin" http://localhost:3000/login
我的系统能够工作。但在下次请求时,我的登录信息就“丢失”了。 这是因为curl不能处理会话吗?有什么解决方法吗? 对于RESTful应用程序,我的步骤是否正确?
curl --cookie cookies.txt --cookie-jar newcookies.txt http://www.example.com
。我每次都要使用这个命令吗?所以:curl --cookie cookies.txt --cookie-jar newcookies.txt --data "username=admin&password=admin" http://localhost:3000/login
然后curl --cookie cookies.txt --cookie-jar newcookies.txt http://localhost:3000/test
?我试过了。当调用/test时,我仍然得到:未经授权。:( - mosquito87--cookie-jar
/-c
的工作方式理解有误(由于某些原因,我以为它可以读写 cookie jar,但实际上它只能写入 cookie 而无法读取)。我已经编辑了我的回答,请尝试新版本。 - nwkjarfile
和执行curl -v --cookie jarfile "http://localhost:3000/test"
命令所得到的输出。或许需要在您的Node.js 应用程序中进行一些更改。 - nwk