4

I am working on adding authentication to a Node/Express site. My authentication is using passport. Authentication works fine for routes but allows a user to guess a url and directly access an image/video/etc. without logging in.

How can I prevent this? I've searched over the documentation on express and passport but am not seeing any solutions?

Mike
  • 185
  • 2
  • 9
  • 2
    My guess would be to ensure your auth middleware gets ran on requests to static resources as well. You won't find documentation for it because it's no different than requiring authentication for any other route. – Kevin B Jul 20 '15 at 19:35

3 Answers3

2

This is similar to the solution @eephillip came up with for serving private static assets/files: Using express.static middleware in an authorized route

He also created his own auth.ensureAuthenticated() handler but it's pretty much the same as this: Documentation for "ensureAuthentication" "isAuthenticated" passport's functions?

Community
  • 1
  • 1
Alexandra
  • 4,723
  • 3
  • 26
  • 32
1

Just make sure your authentication middleware is added before the static one. Of course this authentication middleware should be able to let some requests pass (like the ones to get the login page for example).

gfpacheco
  • 2,831
  • 2
  • 33
  • 50
0

Are you using an API such as instagram by any chance? The passport for instagram includes this function:

function ensureAuthenticated(req,res,next){
  if(req.isAuthenticated()){
    console.log("USER IS AUTHENTICATED");
    return next();
  }
  console.log("USER IS NOT AUTHENTICATED");
  res.redirect('/home');
}

Which can be placed at the top of your routing file to redirect users to a landing page (like /home) if they have not been authenticated during that session.

An example and more information can be found here: https://github.com/jaredhanson/passport-instagram/blob/master/examples/login/app.js or with a google search of instagram passport

prcbass
  • 339
  • 1
  • 3
  • 17