- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用 passport
、express-session
和 connect-pg-simple
。
问题是 session 没有从存储中正确获取,它被正确地(我希望,但怀疑)保存。
我的设置与我在周围找到的许多教程中的设置相同。
服务器.js:
import express from 'express';
import next from 'next';
import bodyParser from 'body-parser';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
const sessionStorage = connectPgSimple(session);
import initAuthentication from '!/server/authentication';
const dev = process.env.NODE_ENV !== 'production'; // eslint-disable-line
const port = process.env.PORT || 3000; // eslint-disable-line
const app = next({ dev });
app.prepare()
.then(() => {
const server = express();
server.use(express.static('public'));
/* Note Since version 1.5.0, the cookie-parser middleware no longer needs
to be used for this module to work. This module now directly reads and writes
cookies on req/res. Using cookie-parser may result in issues
if the secret is not the same between this module and cookie-parser.
https://www.npmjs.com/package/express-session */
// server.use(cookieParser());
server.use(bodyParser.json()); // for parsing application/json
server.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
server.use(session({
secret: 'keyboard cat',
store: new sessionStorage(),
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 30 * 24 * 60 * 60 * 1000
}})
);
initAuthentication(server);
});
authentication.js:
import passport from 'passport';
import LocalStrategy from 'passport-local';
import bcrypt from 'bcrypt';
import {User} from '!/server/db';
import util from 'util';
User.prototype.validPassword = function(password) {
return bcrypt.compareSync(password, this.passwordHash);
};
User.authenticate = (username, password, done) => {
User.findOne({where: {nickname: username}}).then(user => {
if (!user) {
return done(null, false, { message: 'Неверное имя пользователя.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Неверный пароль.' });
}
return done(null, user);
}).catch(err => {
return done(err);
});
};
export default function initAuthentication(server) {
server.use(passport.initialize());
server.use(passport.session());
passport.use('local-signIn', new LocalStrategy(User.authenticate));
passport.serializeUser((user, done) => {
console.log('> serializeUser "'+user.nickname+'" ('+user.id+')');
done(null, user.id);
});
passport.deserializeUser((id, done) => {
console.log('> deserializeUser with id: ' + id)
User.findById(id).then(user => {
done(null, user);
}).catch(error => {
console.log('Error in passport.deserializeUser: ' + error);
done(error, null);
});
});
server.post('/user/login',
passport.authenticate('local-signIn'),
(req, res) => {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
console.log('Authenticated user "'+req.user.nickname+'"');
req.login(req.user, (err)=> {
if (err) console.log(err);
console.log('\t Session established for user "'+req.user.nickname+'"');
res.json(req.user);
});
}
);
function logAuthenticationStatus(req, res, next) {
console.log('Authentication status:')
console.log('\treq.cookies: ' + util.inspect(req.cookies));
console.log('\treq.isAuthenticated: ', req.isAuthenticated());
console.log('\treq.session: ', req.session);
if (req.user) {
console.log('\tLogged in as "'+req.user.nickname+'"');
} else {
console.log('\tNot logged in');
}
next();
}
server.use(logAuthenticationStatus);
server.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
}
有趣的部分是“express-session”的调试输出,这要归功于惊人的 npm-package debug .
因此,当对 /user/login
的请求到来时,用户名=AntonAL,会发生以下情况:
Executing (default): SELECT "id", "nickname", "email", "password", "passwordHash", "lastLoggedIn", "createdAt", "updatedAt" FROM "users" AS "user" WHERE "user"."nickname" = 'AntonAL' LIMIT 1;
> serializeUser "AntonAL" (1)
Authenticated user "AntonAL"
> serializeUser "AntonAL" (1)
Session established for user "AntonAL"
express-session saving qiQfhyAvDDPD7muJLtGdZudKqMug0aAC +23ms
express-session split response +0ms
express-session set-cookie connect.sid=s%3AqiQfhyAvDDPD7muJLtGdZudKqMug0aAC.0wIcunkcEjhaUzs4H7w4uuv6u%2FBKXMROuAm6%2FG0vVQw; Path=/; Expires=Sat, 30 Sep 2017 10:55:31 GMT; HttpOnly +1ms
info: POST /user/login 200 50ms statusCode=200, url=/user/login, host=localhost:3000, content-type=application/json, origin=http://localhost:3000, accept-encoding=gzip, deflate, connection=keep-alive, accept=application/json, user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8, referer=http://localhost:3000/user/login, content-length=44, accept-language=ru, method=POST, httpVersion=1.1, originalUrl=/user/login, , responseTime=50, user=AntonAL
所以,session是保存在db中的,我们看一下:
SELECT * FROM session WHERE sid='qiQfhyAvDDPD7muJLtGdZudKqMug0aAC';`
sid | sess | expire
----------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+---------------------
qiQfhyAvDDPD7muJLtGdZudKqMug0aAC | {"cookie":{"originalMaxAge":2592000000,"expires":"2017-09-30T10:55:31.514Z","secure":false,"httpOnly":true,"path":"/"},"passport":{"user":1}} | 2017-09-30 13:55:32
(1 row)
到目前为止,还不错。
现在,我正在请求一个网站的主页并获得以下信息:
info: GET / 200 486ms statusCode=200, url=/, host=localhost:3000, accept-encoding=gzip, deflate, cookie=connect.sid=s%3AO6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE.M4iFzpVZP9fNa%2FLEomsMD8D9LjA1uFnDMnXT%2FHR3wyk; meteor_login_token=4YvVuK0V4adQJaMM2setEAx9_Ki7q6At19YfAvwyOJ8; _ga=GA1.1.1413606909.1501852025, connection=keep-alive, upgrade-insecure-requests=1, accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8, referer=http://localhost:3000/user/login, cache-control=max-age=0, accept-language=ru, method=GET, httpVersion=1.1, originalUrl=/, , responseTime=486, user=null
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +516ms
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +1ms
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +4ms
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +1ms
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +1ms
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +0ms
express-session no session found +1ms
Authentication status:
req.cookies: undefined
req.isAuthenticated: false
req.session: Session {
cookie:
{ path: '/',
_expires: 2017-09-30T11:15:52.123Z,
originalMaxAge: 2592000000,
httpOnly: true,
secure: false } }
Not logged in
express-session no session found +7ms
我明白了,'express-session' 试图获取 session 与另一个 SID O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE
,数据库中不存在。
为什么会这样?
AFAIK,它应该通过 SID = qiQfhyAvDDPD7muJLtGdZudKqMug0aAC
获取 ...
我的设置有什么问题?
一个秘钥,'cookie-parser' 没有使用,根据recommentation 'Note Since version 1.5.0, the cookie-parser middleware no longer needs' ...
我完全被这个困住了。
请帮忙。
sid 生成有问题
当我手动更改存储 session 的 sid
以使其与 express-session
的请求相匹配时,
UPDATE session SET sid='O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE' WHERE sid='qiQfhyAvDDPD7muJLtGdZudKqMug0aAC';
正确获取 session 并保留用户:
express-session fetching O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +3s
express-session session found +2ms
> deserializeUser with id: 1
Executing (default): SELECT "id", "nickname", "email", "password", "passwordHash", "lastLoggedIn", "createdAt", "updatedAt" FROM "users" AS "user" WHERE "user"."id" = 1;
Authentication status:
req.cookies: undefined
req.isAuthenticated: true
req.session: Session {
cookie:
{ path: '/',
_expires: 2017-09-30T10:55:31.514Z,
originalMaxAge: 2592000000,
httpOnly: true,
secure: false },
passport: { user: 1 } }
Logged in as "AntonAL"
express-session saving O6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE +577ms
express-session split response +1ms
info: GET / 200 585ms statusCode=200, url=/, host=localhost:3000, accept-encoding=gzip, deflate, cookie=connect.sid=s%3AO6rS2cPlQ6JDaUUxxYRAg-VI5MmldaRE.M4iFzpVZP9fNa%2FLEomsMD8D9LjA1uFnDMnXT%2FHR3wyk; meteor_login_token=4YvVuK0V4adQJaMM2setEAx9_Ki7q6At19YfAvwyOJ8; _ga=GA1.1.1413606909.1501852025, connection=keep-alive, upgrade-insecure-requests=1, accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8, referer=http://localhost:3000/user/login, cache-control=max-age=0, accept-language=ru, method=GET, httpVersion=1.1, originalUrl=/, , responseTime=585, user=AntonAL
所以,现在很清楚了——sid 参数在生成 session 和获取 session 时是不同的。
最佳答案
想通了。
在客户端代码中,我使用了带有以下代码的fetch
函数:
fetch('/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values)
});
这种方法给了我问题。
当我在路由中将请求方法更改为“GET”并使用普通重定向时,一切正常。
window.location.href = "/login?"+querystring.stringify(values);
为什么会这样?
关于node.js - 使用 express-session 和 passportjs 未从存储中正确获取 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980476/
是否为每个 Shiny session 分配了 session ID/ session key (如果部署在 Shiny 服务器上)?如果是,我如何访问该信息?我已阅读文档here然而上网查了一下,并
我正在使用 this koajs session 模块。 我检查了源代码,但我真的无法理解。 我想知道它保存 session 数据的位置,因为我没有看到创建的文件,并且当服务器重新启动时, sessi
实现高可扩展性的一种方法是使用网络负载平衡在多个服务器之间分配处理负载。 这种方法提出的一个挑战是服务器是否具有状态意识 - 将用户状态存储在“ session ”中。 此问题的一个解决方案是“粘性
在负载平衡服务器的上下文中, session 亲和性和粘性 session 之间有什么区别? 最佳答案 我见过这些术语可以互换使用,但有不同的实现方式: 在第一个响应中发送 cookie,然后在后续响
我希望其他人向我解释哪种方法更好:使用 session 或设计无 session 。我们正在开始开发一个新的 Web 应用程序,但尚未决定要遵循什么路径。 无 session 设计在我看来更可取: 优
现在用户在他的权限中有很多角色,我将允许他点击 href 并在新窗口中扮演另一个角色。每个角色都有自己的 session 。 既然浏览器打开窗口不能用新 session 打开,我必须在服务器端想办法。
我正在尝试为express.js Node 应用程序实现 session 存储我的问题是: 如何删除具有浏览器 session 生命周期的 cookie(根据连接文档标记有 expires = fal
在开始在 golang 中使用 session 之前,我需要回答一些问题 session 示例 import "github.com/gorilla/sessions" var store = ses
我读过 Namespaced Attributes . 我尝试使用此功能: #src/Controller/CartController.php public function addProduct(
我正在努力完成以下工作: 根据用户的类型更改用户的 session cookie 到期日期。 我有一个 CakePHP Web 应用程序,其中我使用 CakePHP session 创建了我的身份验证
这是我在这里的第一个问题,我希望我做对了。 我需要处理一个 Java EE 项目,所以在开始之前,我会尝试做一些简单的事情,看看我是否能做到。 我坚持使用有状态 session Bean。 这是问题:
ColdFusion session 与 J2EE session 相比有什么优势吗? ColdFusion session documentation提到了 J2EE session 的优点,但没有
在执行任何任务之前,我需要准确地在创建 session 时创建一个 session 范围变量(因为我的所有任务都需要一个初始 session 范围变量才能运行)。因为,创建 session 时,gra
我们当前的应用使用 HTTP session ,我们希望将其替换为 JWT。 该设置仅允许每个用户进行一次 session 。这意味着: 用户在设备 1 上登录 用户已在设备 1 上登录(已创建新 s
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
假设我在两个或更多设备上打开了两个或更多用户 session (同一用户没有管理员权限)。 在当前 session 中,如果我注销,是否意味着所有其他 session 也会关闭?如果没有,有没有办法通
我正在评估在 tomcat 中使用带有 session 复制的粘性 session 的情况。根据我的初步评估,我认为如果我们启用 session 复制,那么在一个 tomcat 节点中启动的 sess
我开始使用 golang 和 Angular2 构建一个常规的网络应用程序,最重要的是我试图在 auth0.com 的帮助下保护我的登录.我从 here 下载快速入门代码并尝试运行代码,它运行了一段时
我在 Spring Controller 中有一个方法,它接受两个相同类型的参数其中一个来自 session ,另一个来自表单提交(UI)。 问题是在 Controller 方法中我的非 sessio
在我登录之前,我可以点击我的安全约束目录之外的任何内容。如果我尝试转到安全约束目录内的某个位置,它会将我重定向到表单登录页面。如您所料。 登录后,我可以继续我的业务,并访问我的安全约束内外的资源。
我是一名优秀的程序员,十分优秀!