Express.js 4 - use middleware for authentication before static files
Solution 1
Since you didn't specify it, I'm going to assume that you already have some kind of authentication system.
In Express, the order of the middlewares in the code matters: if you want to have middleware 1 executed before middleware 2, you should place them accordingly in your code. Since express.static
is a middleware, if you want authentication before serving your static files you can simply write your authentication middleware before the call to express.static
app.use(function (req, res, next) {
if (!userAuthenticated(req)) {
return res.redirect('/login');
}
next();
});
app.use(express.static(__dirname + '/public'));
I am assuming you have a userAuthenticated
function which is for instance checking if the HTTP requests contains a valid access-token.
Solution 2
Check out Passport.
Passport has many authentication strategies.
Here's an example with basic HTTP authentication:
var express = require('express');
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var db = require('./db');
// Configure the Basic strategy for use by Passport.
//
// The Basic strategy requires a `verify` function which receives the
// credentials (`username` and `password`) contained in the request. The
// function must verify that the password is correct and then invoke `cb` with
// a user object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new BasicStrategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false); }
if (user.password != password) { return cb(null, false); }
return cb(null, user);
});
}));
// Create a new Express application.
var app = express();
var authenticate = passport.authenticate('basic', {
session: false,
failureRedirect: '/login'
});
app.use(authenticate, express.static(__dirname + '/public'));
Radoslav Stoyanov
Passionate developer, keen on good coding practices and new technologies, experienced in containerization and continuous integration and delivery.
Updated on June 15, 2022Comments
-
Radoslav Stoyanov almost 2 years
In my
express
app I've set static files to be served from the/public
directory with this line:app.use(express.static(__dirname + '/public'));
Now I need to add a middleware for authentication before serving the static content and if the user is not authenticated to be redirected to a route for authentication (e.g.,
/login
).
I'm not really sure how I have to do it. Any ideas? -
Radoslav Stoyanov about 8 yearsGreat! Thank you for the solution! I was considering something similar but I wasn't sure for the implementation and if I am able to make such kind of redirect at this point. Thanks again!
-
Ivan Ferrer Villa over 6 yearsthanks! Your answer helped me to solve the static files question but also to understand better how express middlewares work. Everything makes sense now