是的,你可以,这只是中间件!这是您将如何做的示例,我没有运行此代码,因此它可能无法构建,但它显示了如何做您所追求的。
const express = require('express');
const passport = require('passport');
const passportJWT = require('passport-jwt');
// My express application where I setup routers, middleware etc
const app = express();
// Initialise passport
app.use(passport.initialize());
// Setup my passport JWT strategy, this just setups the strategy it doesn't mount any middleware
passport.use(new passportJWT.Strategy({
secretOrKey: '',
issuer: '',
audience: '',
}, (req, payload, done) => {
doSomeFancyAuthThingy(payload, (err, user) => {
done(err, user);
});
}));
// Now create some middleware for the authentication
app.use((req, res, next) => {
// Look to see if the request body has a customerId, in reality
// you probably want to check this on some sort of cookie or something
if (req.body.customerId) {
// We have a customerId so just let them through!
next();
} else {
// No customerId so lets run the passport JWT strategy
passport.authenticate('jwt', (err, user, info) => {
if (err) {
// The JWT failed to validate for some reason
return next(err);
}
// The JWT strategy validated just fine and returned a user, set that
// on req.user and let the user through!
req.user = user;
next();
});
}
});
如您所见,您要寻找的主要内容是我们创建中间件的位置。这里我们只是创建自己的中间件并运行检查(if 语句),如果失败则运行 passport.authenticate,它会触发我们在 passport.use 块上创建的策略。
这将允许您有条件地使用 Passport 进行任何类型的身份验证!