当请求包含授权标头时,阻止Expressjs创建会话?

Oli*_*oyd 8 connect node.js express passport.js

我有一个API,可以使用浏览器调用,其中请求是事务性的,并且直接具有会话OR,例如.使用curl,其中请求是原子的.浏览器请求必须首先进行身份验证,然后使用快速会话(connect.sid)进行后续授权,直接API调用使用标头:Authorization: "SOMETOKEN"必须为每个请求发送标头.

我遇到的问题是,因为我使用相同的Web服务器来提供原子和事务流量,所以每次API调用都会被Express发送给会话.每个响应都包含一个Set-Cookie,所有这些会话都填满了我的会话存储.因此:当请求包含Authorization标头时,如何阻止Express在内存存储区(Redis)中输入新的sess密钥?

注意.我得到一个更经典的方法是拥有一个单独的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());
        }
    });

};
Run Code Online (Sandbox Code Playgroud)

示例路线

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

授权中间件

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
    }
};
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 18

试试这个:

var sessionMiddleware = exp.session( session_options );

app.use(function(req, res, next) {
  if (req.headers.authorization) {
    return next();
  }
  return sessionMiddleware(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)