Reputation: 1700
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?
Upvotes: 4
Views: 11118
Reputation: 3874
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.
Upvotes: 12
Reputation: 695
Depends on what kind of authentication you are looking for, but if you just want some login-feature, this is what you need: http://passportjs.org/
It has support for local login strategies, as well as a whole bunch of 3rd party strategies like facebook, twitter, etc.
If you need something else, simpler or self-made, just write a middleware to use before you declare the static endpoint, and call next() if everything checks out, and res.redirect if user needs to retry.
Upvotes: 0
Reputation: 748
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'));
Upvotes: 3