Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 560
Zlatko Avatar asked Sep 01 '14 09:09

Zlatko


People also ask

How do you protect Express routes?

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.

What are routes in Express what do they represent and how do we use them?

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.

How can we create Chainable route handlers for a route path in Expressjs app?

Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.


1 Answers

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);
like image 199
Ben Fortune Avatar answered Oct 13 '22 23:10

Ben Fortune