【发布时间】:2014-02-11 10:44:14
【问题描述】:
我有一个 API,可以使用浏览器调用,其中请求是事务性的并且有会话,或者直接调用,例如。使用 curl,其中请求是原子的。浏览器请求必须首先进行身份验证,然后使用快速会话 (connect.sid) 进行后续授权,直接 API 调用使用标头:Authorization: "SOMETOKEN",每个请求都必须发送该标头。
我遇到的问题是,因为我使用同一个 Web 服务器来提供原子流量和事务流量,所以 Express 不必要地为每个 API 调用提供了一个会话。每个响应都包含一个 Set-Cookie,所有这些会话都填满了我的会话存储。因此:当请求包含 Authorization 标头时,如何防止 Express 在内存存储 (Redis) 中输入新的 sess key?
注意。我知道一个更经典的方法是拥有一个单独的 API 服务器和一个单独的 WEB 服务器,但为什么不在一台机器上同时运行呢?对我来说,区别在于 API 服务于数据,而 WEB 服务于视图,但除此之外,它们都是同一个应用程序的一部分。我只是碰巧还允许用户直接访问他们的数据,而不是强迫他们使用我的界面。
快速配置
module.exports = function(app, exp, sessionStore, cookieParser, passport, flash) {
app.configure(function(){
// Templates
app.set('views', ERNEST.root + '/server/views');
app.set('view engine', 'jade');
app.set('view options', { doctype : 'html', pretty : true });
// Allow large files to be uploaded (default limit is 100mb)
app.use(exp.limit('1000mb'));
// Faux putting and deleting
app.use(exp.methodOverride());
// Static content
app.use(exp.static(ERNEST.root + '/server'));
app.use(exp.static(ERNEST.root + '/public'));
// Handle favicon
app.use(exp.favicon());
// For uploads
app.use(exp.bodyParser({keepExtensions: true}));
// Configure cookie parsing
if ( cookieParser ) app.use(cookieParser);
else app.use(exp.cookieParser());
// Where to store the session
var session_options = { 'secret': "and she put them on the mantlepiece" };
if ( sessionStore ) session_options.store = sessionStore;
app.use(exp.session( session_options ));
// Rememberance
app.use( function (req, res, next) {
if ( req.method == 'POST' && req.url == '/authenticate' ) {
if ( req.body.rememberme === 'on' ) {
req.session.cookie.maxAge = 2592000000; // 30*24*60*60*1000 Rememeber 'me' for 30 days
} else {
req.session.cookie.expires = false;
}
}
next();
});
// PassportJS
if ( passport ){
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
}
});
};
示例路线
app.get('/status/past_week', MID.ensureAuthenticated, MID.markStart, function(req, res) {
WEB.getStatus('week', function(err, statuses){
if ( err ) res.send(500, err);
else res.send(200, statuses);
});
});
授权中间件
MID.ensureAuthenticated = function(req, res, next) {
if ( req.isAuthenticated() ) return next();
else {
isAuthorised(req, function(err, authorised){
if ( err ) return res.redirect('/');
else if ( authorised ) return next();
else return res.redirect('/');
});
}
function isAuthorised(req, callback){
var authHeader = req.headers.authorization;
if ( authHeader ) {
// Has header, verify it
var unencoded = new Buffer(authHeader, 'base64').toString();
var formatted = unencoded.toString().trim();
ACCOUNT.verifyAuth(formatted, callback); // verifyAuth callbacks next() when successful
} else callback(null, false); // No Authorised header
}
};
【问题讨论】:
标签: node.js express connect passport.js