问题
Suppose I have the code like this:
var api1 = require('api1');
var api2 = require('api2');
var app = express();
app.use('/api1', api1);
app.use('/api2', api2);
Here is the code for api1 module:
var router = express.Router();
var options = {
jwtFromRequest:ExtractJwt.fromAuthHeader(),
secretOrKey:config.JWTSecret,
algorithms:['HS256']
}
passport.use(new JwtStrategy(options, function(jwt_payload, verify) {
//here I look for the user in database No.1
}));
router.post('/files', passport.authenticate('jwt', { session: false}), function(req, res) {
//...
}
module.exports = router;
And this is is the code for api2 module:
var router = express.Router();
var options = {
jwtFromRequest:ExtractJwt.fromAuthHeader(),
secretOrKey:config.JWTSecret,
algorithms:['HS256']
}
passport.use(new JwtStrategy(options, function(jwt_payload, verify) {
//here I look for the user in database No.2
}));
router.post('/files', passport.authenticate('jwt', { session: false}), function(req, res) {
//...
}
module.exports = router;
This woun't work. In both cases, if I make POST to "/api1/files" and to "/api2/files" it will look for the user in database No2. If there is no solution for this problem, using passport.js api, what are the other posssible approaches for dealing with such kind of issue?
回答1:
The trick to this is using the named strategy syntax. Basically when you call passport.use()
you can pass an optional first param that tells passport the name of the strategy, then use that name (rather than the default) with the authenticate
call. So in your case you could do something like:
passport.use('jwt-1', new JwtStrategy(options, function(jwt_payload, verify) {
//here I look for the user in database No.1
}));
router.post('/files', passport.authenticate('jwt-1', { session: false}), function(req, res) {
//...
}
Your api2 would then name its strategy 'jwt-2' or whatever makes sense to you.
来源:https://stackoverflow.com/questions/37846711/how-to-use-the-same-passport-strategy-for-different-routes