将护照 openID 策略与 JWT 相结合
Combining a passport openID-stategy with JWT
我 运行 在尝试使用 openID (passport-steam) 通过 passport.js 进行身份验证时遇到了问题,然后使用令牌 (JWT) 而不是会话。
我当前的代码如下所示:
app.post('/auth/steam', passport.authenticate('steam'));
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/', session: false }),
function(req, res) {
var token = jwt.encode({ useridentifier: req.user.identifier}, tokenSecret);
res.redirect('/');
});
但是,我遇到的问题是:我应该如何将令牌传回客户端?由于这是从 Steam 站点返回后 运行 的 GET 请求,我无法用简单的
回复
res.json(token)
就像我看到人们将本地策略与 JWT 一起使用一样。
我想出的唯一解决方案涉及使用包含令牌的会话(例如 connect-flash),并在客户端被重定向到 '/ ',但使用 JWT 的全部意义在于避免使用会话,不是吗?
经过多日无果的思考,我想出了另一种解决方法,那就是使用 cookie。
我发现了 passport 提供的自定义回调,我可以在其中设置响应的 headers,所以我在重定向之前设置了这样一个:
res.cookie('token', token, { httpOnly: true });
(还不安全,因为我只在本地服务器上测试)
这就是整个代码现在的样子:
app.get('/auth/steam', passport.authenticate('steam'));
app.get('/auth/steam/return',
function(req, res, next) {
passport.authenticate('steam', function(err, user, info){
var payload = {
user: user.identifier
};
var token = jwt.sign(payload, "thisisnotthesecretiactuallyuse", {expiresIn : 60*60*24});
res.cookie('token', token, { httpOnly: true /* TODO: Set secure: true */ });
res.redirect('/');
})(req, res, next)
});
我 运行 在尝试使用 openID (passport-steam) 通过 passport.js 进行身份验证时遇到了问题,然后使用令牌 (JWT) 而不是会话。
我当前的代码如下所示:
app.post('/auth/steam', passport.authenticate('steam'));
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/', session: false }),
function(req, res) {
var token = jwt.encode({ useridentifier: req.user.identifier}, tokenSecret);
res.redirect('/');
});
但是,我遇到的问题是:我应该如何将令牌传回客户端?由于这是从 Steam 站点返回后 运行 的 GET 请求,我无法用简单的
回复res.json(token)
就像我看到人们将本地策略与 JWT 一起使用一样。
我想出的唯一解决方案涉及使用包含令牌的会话(例如 connect-flash),并在客户端被重定向到 '/ ',但使用 JWT 的全部意义在于避免使用会话,不是吗?
经过多日无果的思考,我想出了另一种解决方法,那就是使用 cookie。
我发现了 passport 提供的自定义回调,我可以在其中设置响应的 headers,所以我在重定向之前设置了这样一个:
res.cookie('token', token, { httpOnly: true });
(还不安全,因为我只在本地服务器上测试)
这就是整个代码现在的样子:
app.get('/auth/steam', passport.authenticate('steam'));
app.get('/auth/steam/return',
function(req, res, next) {
passport.authenticate('steam', function(err, user, info){
var payload = {
user: user.identifier
};
var token = jwt.sign(payload, "thisisnotthesecretiactuallyuse", {expiresIn : 60*60*24});
res.cookie('token', token, { httpOnly: true /* TODO: Set secure: true */ });
res.redirect('/');
})(req, res, next)
});