What is a better way to authenticate some of the routes on Express 4 Router?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-20 10:54:15

问题


I'm using Express 4 where I have a route protected by passport.js, like this:

var media = require('express').Router();

media.get('/', function(req, res) {
    // provide results from db
});

media.post('/', passport.authenticate('bearer'), function(req, res) {
    // This route is auth protected
});

So - get collection routes should (mostly) not be protected for me, and create/update routes should. But this requires me to pass passport to all my route files (I have 7 so far), then to add that as a middleware to some of them.

I like the version where you can do something like this:

var router = require('./my-router');
app.use('/api/route', passport.authenticate('bearer'));
app.use('/api/route', router);

But this would require auth on all my routes.

Is there a better way then to pass passport all the way around?


回答1:


You could split your router up into protected/unprotected and call the middleware on the protected routes.

var express = require('express'),
    media = express.Router(),
    mediaProtected = express.Router();

media.get('/', function(req, res) {
    // provide results from db
});

mediaProtected.post('/', function(req, res) {
    // This route is auth protected
});

module.exports = {
    protected: mediaProtected,
    unprotected: media
};

And then you can do

var router = require('./my-router');
app.use('/api/route', passport.authenticate('bearer'), router.protected);
app.use('/api/route', router.unprotected);


来源:https://stackoverflow.com/questions/25602948/what-is-a-better-way-to-authenticate-some-of-the-routes-on-express-4-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!