我有这个Node API,它支持后端OAuth服务器。在SAML OAuth舞蹈结束时,我将Bearer Token设置为浏览器cookie。
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined)
{
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
}
else
{
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next();
});
app.use(express.static(__dirname + '/public'));
现在我被介绍给一个花哨的NPM,它做了几乎相同的事情https://github.com/mozilla/node-client-sessions
虽然我几乎倾向于使用这个NPM,但我遇到了快速会议。 https://github.com/expressjs/session - 这适用于服务器端会话。但这也设置了一个cookie
var express = require('express');
var session = require("express-session");
var app = express();
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'ABC123',
cookie: {
maxAge: 60000
}
}));
app.get("/test", function(req, res) {
req.session.user_agent = req.headers['user-agent'];
res.send("session set");
});
如果我需要在浏览器cookie中仅为后续API调用设置一个不记名令牌,那么我应该选择哪个选项?
答案 0 :(得分:8)
express-session
是我的目标。
如果你看看用两种不同的方法完成同样的事情,我认为答案是清楚的。
如果你想要做的就是设置一个客户端cookie,使服务器能够正确地验证未来的请求,那么express-session就很棒了。
以下是来自another question I answered的示例集,它使用MongoDB作为后端来存储会话:
'use strict';
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
mongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/someDB');
var app = express();
var secret = 'shhh';
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret,
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions' // default
})
}));
// ROUTES, ETC.
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});