如何对不同的路线使用相同的护照策略? [英] How to use the same passport strategy for different routes?

查看:89
本文介绍了如何对不同的路线使用相同的护照策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

var api1 = require('api1');
var api2 = require('api2');
var app = express();
app.use('/api1', api1);
app.use('/api2', api2);

以下是api1模块的代码:

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;

这是api2模块的代码:

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;

这不起作用。在这两种情况下,如果我对/ api1 / files和/ api2 / files进行POST,它将查找用户数据库No2。如果没有这个问题的解决方案,使用passport.js api,其他posssibl是什么处理此类问题的方法是什么?

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?

推荐答案

这方面的诀窍是使用命名策略语法。基本上,当您调用 passport.use()时,您可以传递一个可选的第一个参数,告诉护照策略的名称,然后使用该名称(而不是默认值) 验证电话。所以在你的情况下你可以这样做:

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) {
   //...
}

您的api2会将其策略命名为jwt-2或任何有意义的名称给你。

Your api2 would then name its strategy 'jwt-2' or whatever makes sense to you.

这篇关于如何对不同的路线使用相同的护照策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆