Express Authentication Redirects Leading to Infinite Loop

authentication, express, infinite-loop, node.js, passport.js

Solution

So I'm guessing you're letting `express.static()` handle the requests for `index.html` and `login.html`? In that case, you could create a route for `index.html` that would first check authentication, and act accordingly:

app.get('/index.html', ensureAuthenticated, function(req, res, next) {
  // if this block is reached, it means the user was authenticated;
  // pass the request along to the static middleware.
  next();
});

Make sure that the above route is declared before you add `express.static` to the middleware stack, otherwise it will get bypassed (Express middleware/routes are called in order of declaration, the first one that matches the request will get to handle it).

EDIT: I keep forgetting that this is possible, and much cleaner, too:

app.use('/index.html', ensureAuthenticated);

(instead of the `app.get` above)

Problem

I am attempting to set up a passport-local authentication on a node.js server using express. It seems like it should be very straight forward. But I am getting stuck. these two snippets work fine together: ``` app.get('/', ensureAuthenticated, function(req, res){ res.redirect('/index.html', { user: req.user }); }); app.post('/login', passport.authenticate('local', { failureRedirect: '/login.html', failureFlash: true, successFlash: "Success!" }), function(req, res) { res.redirect('/'); }); ``` The issue is there is nothing keeping me from typing "www.myurl.com/index.html" into the address bar and dropping right onto my page. if I use a any code like this: ``` app.get('/index.html', ensureAuthenticated, function(req, res){ res.redirect('/index.html', { user: req.user }); }); ``` It seems like i get caught in a loop... it would be nice if it could check my authentication and send me on my way, without eternally checking on each redirect. What is the method of avoiding this? I noticed that the documentation seems to utilize .render, instead of redirect. But this SEEMS to require that I use .ejs and I would prefer not to do that. Is this a must? ++For Reference++ ``` function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login.html') } ```

Original source