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?
The ensureAuthenticated function is just an example, you can define your own function. Calling next() continues the request chain. No idea, if you want to protect a set path you can use middleware e.g app. use('/user/*', ensureAuthenticated) will protect any matching routes.
A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern. There are several ways to create routes.
Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With