问题
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