意思是,在我的应用程序中,我想检查客户端请求中是否存在customId。如果是,我将使用我的自定义逻辑继续进行身份验证。 如果customId不存在,我想使用passport-jwt身份验证。
passport在服务器启动时注册其初始化方法。 我的具体问题是,如果customId不存在,我该如何使用passport.authenticate。
非常感谢任何帮助。
答案 0 :(得分:1)
是的,你可以,它只是中间件!以下是您如何操作的示例,我没有运行此代码,因此可能无法构建,但它会显示如何执行您之后的操作。
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进行任何类型的身份验证!