【问题标题】:How to set different Passport JS Bearer strategy per endpoint and REST methods?如何为每个端点和 REST 方法设置不同的 Passport JS Bearer 策略?
【发布时间】:2019-07-15 21:01:18
【问题描述】:

我正在使用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 执行相同操作。 谢谢。

【问题讨论】:

    标签: javascript node.js express passport.js


    【解决方案1】:

    与教程中的相同。为策略设置一些标签,然后参考它。

    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 
    });
    
    

    【讨论】:

    • 第二个代码块中的括号不匹配。
    猜你喜欢
    • 2017-10-07
    • 2019-06-08
    • 2012-10-03
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多