如何使用护照身份验证更新包含 jwt 的 cookie
How to update cookie containing jwt using passport authentication
我有一个包含签名 jwt 的 cookie,有效期为 5 分钟。 jwt 包含基本用户信息(用于身份验证)以及全局唯一 ID (guid)。如果这些 guid 有效,我将它们存储在数据库中,并且在 jwt 到期后的下一个请求中,我想:
1.) 检查数据库中的 guid 是否仍然有效(未列入黑名单)
2.) 使用新的 5 分钟有效期和相同的信息更新 cookie 中的 jwt
我 运行 犯了很多错误,但我尝试过的任何一个都没有奏效,我很好奇这是否可行或此时的正确方法。
我正在使用节点 js 包 "passport-jwt" 结合 "jsonwebtoken" 创建 jwts 并验证它们。
//////////////////////
//authorization.js
//////////////////////
const JWTStrategy = require('passport-jwt').Strategy;
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
require('../models/Guids');
const Guids = mongoose.model('Guids');
module.exports.JWTStrategy = function (passport) {
passport.use('jwt', new JWTStrategy({
jwtFromRequest: req => cookieExtractor(req, 'token'),
secretOrKey: 'secret',
passReqToCallback: true
},
(req, jwt_payload, done) => {
if (Date.now() / 1000 > jwt_payload.exp) {
Guids.findOne({ _id: jwt_payload.guid, userId: jwt_payload.uid })
.then(guid => {
if (guid.valid) {
//REFRESH TOKEN HERE
//????????return done(null, jwt_payload);
} else {
//FORCE USER TO RE-AUTHENTICATE
//???????return done('access token expired');
}
})
.catch(err => {
console.log(err);
return done('failed to validate user');
});
} else {
return done(null, jwt_payload);
}
}
));
};
var cookieExtractor = function (req, tokenName) {
var token = null;
if (req && req.cookies) {
token = req.cookies[tokenName];
} else {
console.log('no cookie found');
}
return token;
};
--
/////////////////////////////
//app.js
/////////////////////////////
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const app = express();
require('./authorization').JWTStrategy(passport);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
//Protected Route
app.get('/xyz', passport.authenticate('jwt', {session: false}), (req, res) => {
//route logic....
});
//login Route (creates token)
app.post('/login', (req, res, next) => {
payload = {
guid: 12345678901010101',
uid: '123456789',
};
req.login(payload, { session: false }, (err) => {
if (err) {
console.log(err);
} else {
const token = jwt.sign(payload, 'secret', {expiresIn: '30s'});
res.cookie('token', token, { httpOnly: true });
res.redirect('/xyz');
};
}
}
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
默认情况下,当令牌过期时,受保护路由上的身份验证中间件会立即引发失败。
我想绕过这个失败,而是在注释为 "REFRESH TOKEN HERE".
的 "authorization.js" 文件中执行一些代码
由于自动失败,那一行代码根本就没有达到!我在过期前后尝试过控制台日志记录。
我之前也手动绕过了自动失败,但是passport-jwt策略中没有包含cookies的响应对象(res)。如果指定的位置由于它是一个中间件功能而变得荒谬,那么我应该在哪里实现这个逻辑有点迷茫。
此外,如果受保护的路由是 POST,并且令牌在页面成功 "GET" 后过期,我不想妨碍 POST 方法。我想无缝刷新令牌,然后与 POST.
一起移动
Passport 支持自定义消息,更准确地说,支持自定义回调。您必须自己手动调用 passport authenticate 中间件并将其嵌入到您自己的包装器中间件中。这允许访问 req
和 res
对象。有关详细信息,请参阅 documentation.
If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
我有一个包含签名 jwt 的 cookie,有效期为 5 分钟。 jwt 包含基本用户信息(用于身份验证)以及全局唯一 ID (guid)。如果这些 guid 有效,我将它们存储在数据库中,并且在 jwt 到期后的下一个请求中,我想:
1.) 检查数据库中的 guid 是否仍然有效(未列入黑名单)
2.) 使用新的 5 分钟有效期和相同的信息更新 cookie 中的 jwt
我 运行 犯了很多错误,但我尝试过的任何一个都没有奏效,我很好奇这是否可行或此时的正确方法。
我正在使用节点 js 包 "passport-jwt" 结合 "jsonwebtoken" 创建 jwts 并验证它们。
//////////////////////
//authorization.js
//////////////////////
const JWTStrategy = require('passport-jwt').Strategy;
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
require('../models/Guids');
const Guids = mongoose.model('Guids');
module.exports.JWTStrategy = function (passport) {
passport.use('jwt', new JWTStrategy({
jwtFromRequest: req => cookieExtractor(req, 'token'),
secretOrKey: 'secret',
passReqToCallback: true
},
(req, jwt_payload, done) => {
if (Date.now() / 1000 > jwt_payload.exp) {
Guids.findOne({ _id: jwt_payload.guid, userId: jwt_payload.uid })
.then(guid => {
if (guid.valid) {
//REFRESH TOKEN HERE
//????????return done(null, jwt_payload);
} else {
//FORCE USER TO RE-AUTHENTICATE
//???????return done('access token expired');
}
})
.catch(err => {
console.log(err);
return done('failed to validate user');
});
} else {
return done(null, jwt_payload);
}
}
));
};
var cookieExtractor = function (req, tokenName) {
var token = null;
if (req && req.cookies) {
token = req.cookies[tokenName];
} else {
console.log('no cookie found');
}
return token;
};
--
/////////////////////////////
//app.js
/////////////////////////////
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const app = express();
require('./authorization').JWTStrategy(passport);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
//Protected Route
app.get('/xyz', passport.authenticate('jwt', {session: false}), (req, res) => {
//route logic....
});
//login Route (creates token)
app.post('/login', (req, res, next) => {
payload = {
guid: 12345678901010101',
uid: '123456789',
};
req.login(payload, { session: false }, (err) => {
if (err) {
console.log(err);
} else {
const token = jwt.sign(payload, 'secret', {expiresIn: '30s'});
res.cookie('token', token, { httpOnly: true });
res.redirect('/xyz');
};
}
}
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
默认情况下,当令牌过期时,受保护路由上的身份验证中间件会立即引发失败。
我想绕过这个失败,而是在注释为 "REFRESH TOKEN HERE".
的 "authorization.js" 文件中执行一些代码由于自动失败,那一行代码根本就没有达到!我在过期前后尝试过控制台日志记录。
我之前也手动绕过了自动失败,但是passport-jwt策略中没有包含cookies的响应对象(res)。如果指定的位置由于它是一个中间件功能而变得荒谬,那么我应该在哪里实现这个逻辑有点迷茫。
此外,如果受保护的路由是 POST,并且令牌在页面成功 "GET" 后过期,我不想妨碍 POST 方法。我想无缝刷新令牌,然后与 POST.
一起移动Passport 支持自定义消息,更准确地说,支持自定义回调。您必须自己手动调用 passport authenticate 中间件并将其嵌入到您自己的包装器中间件中。这允许访问 req
和 res
对象。有关详细信息,请参阅 documentation.
If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});