Я использую паспорт-jwt, и есть конечная точка, которая должна возвращать некоторые данные из базы данных, если токен jwt отсутствует в заголовке. Можно ли применить некоторую логику вместо того, чтобы просто отправлять Unauthorized 401?
router.get(
'/get/items',
passport.authenticate('jwt', {session: false}),
(req, res) => {
// reaches this point only after validating token
...
}
);
Поэтому, если токен jwt присутствует, на его основе конечная точка должна возвращать некоторые данные. Если нет, должны быть возвращены некоторые другие данные из БД.





Я думаю, что пользовательский обратный вызов - это вариант. Он передается в качестве последнего параметра методу authenticate(strategy, options, callback) и позволяет вам установить желаемое поведение.
Ваш код будет выглядеть так:
app.get('/get/items', (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (!user) {
/*
Unauthorized accees.
Handle here the request as u wish
*/
/* Do some custom logic and return your desired result */
return res.status(401).json({ success: false, message: 'Unauthorized access!' });
}
/* User is authorized. Do other stuff here and return your desired result*/
return res.status(200).json({ success: true, message: 'Congratulations!' });
})(req, res, next);
});
In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.
If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.
The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.
Оберните промежуточное ПО и обработайте ошибки так, как хотите:
function authenticate(req, res, next) {
passport.authenticate('jwt', { session: false }, (err, user) => {
if (err) {
res.status(err.statusCode || 401).json({ error: err.toString() });
return;
}
if (!user) {
res.status(404).json({ ... });
return;
}
req.user = user;
next();
})(req, res, next);
}
Используйте это вместо этого:
router.get(
'/get/items',
authenticate,
(req, res) => {
// reaches this point only after validating token
...
}
);
Ответы от @codtex и @Dominic решают проблему.
Я узнал, что следующее решение также работает:
router.get(
'/get/items',
passport.authenticate('jwt', {session: false}),
(req, res) => {
// reaches this point only after validating token
...
},
(err, req, res, next) => {
console.info('error handling');
// reaches this point if validation fails
}
);