如何为每个端点和 REST 方法设置不同的 Passport JS Bearer 策略?

How to set different Passport JS Bearer strategy per endpoint and REST methods?

我正在使用 BearerStrategy 并尝试在同一个路由器中为每个端点或方法设置不同的策略。

我查看了文档,除了创建新路由器外,我没有看到任何关于这种情况的参考。

这是我得到的:

const router = express.Router()

passport.use(new BearerStrategy(
  { passReqToCallback: true },
  async function (req, token, done) {
      if (token) { 
      // business logic 
      }
   }));

router.post("/",
 passport.authenticate('bearer', { session: false, passReqToCallback: true, failWithError: true },
  function (req, res, next) { // handle success 
},
  function (err, req, res, next) { // handle failure 
});

router.get("/",
 passport.authenticate('bearer', { session: false, passReqToCallback: true, failWithError: true },
  function (req, res, next) { // handle success 
},
  function (err, req, res, next) { // handle failure 
});

router.get("/:username",
 passport.authenticate('bearer', { session: false, passReqToCallback: true, failWithError: true },
  function (req, res, next) { // handle success 
},
  function (err, req, res, next) { // handle failure 
});

我正在寻找如何为每个端点实现不同的业务逻辑。一个用于 GET /,另一个用于 GET /:usernamePOST / api

in this tutorial 我看到了这个:

    passport.use('local-login', new LocalStrategy({ ... })
    passport.use('local-signup', new LocalStrategy({ ... })

    router.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/auth/profile',
        failureRedirect : 'auth/signup'
    }));

    router.post('/login', passport.authenticate('local-login', {
        successRedirect : '/auth/profile',
        failureRedirect : 'auth/login'
    }));

但无法对 BearerStrategy 执行相同的操作。 谢谢。

和教程里的一样。为策略设置一些标签,然后引用它。

passport.use('GET-strategy', new BearerStrategy(
  { passReqToCallback: true },
  async function (req, token, done) {
      if (token) { 
      // business logic 
      }
   }));


passport.use('POST-strategy', new BearerStrategy(
  { passReqToCallback: true },
  async function (req, token, done) {
      if (token) { 
      // business logic 
      }
   }));

然后:

router.get("/",
 passport.authenticate('GET-strategy', { session: false, passReqToCallback: true, failWithError: true }),
  function (req, res, next) { // handle success 
},
  function (err, req, res, next) { // handle failure 
});

router.post("/",
 passport.authenticate('POST-strategy', { session: false, passReqToCallback: true, failWithError: true }),
  function (req, res, next) { // handle success 
},
  function (err, req, res, next) { // handle failure 
});