Search code examples
node.jsexpresspassport.jsexpress-handlebars

Can Hacker modify the request that is sent to the web server? I am authenticating the user based on a object in the request


I am a beginner to nodejs and I am creating my web app. I use passportJs for authentication. As it is mentioned in the documentation that when the user is successfully authenticated, req.user will be created and can be accessed in any route.

My admin.handlebars

router.get('/' , (req , res)=>{
    const current_user = req.user
    if (!req.user) {
        res.redirect('/login')
    } else{
        res.render('admin/index',{user_data:current_user })
    }
   

})

Authentication using passportJS

passport.use(new LocalStrategy({usernameField:'email'}, (email,password,done)=>{
    
    userModel.findOne({email:email}).then((user)=>{
     if (!user) return done(null,false,{message: "No User found"})
     bcrypt.compare(password,user.password,(err,matched)=>{
        if(err)return err
        if(matched){
            
            return done(null,user)
        }else {return done(null,false,{message:"Incorrect Password"})}


     })

       
    })     
  
 }))


 passport.serializeUser(function(user, done) {
    done(null, user.id);
  });
  
  passport.deserializeUser(function(id, done) {
    userModel.findById(id, function(err, user) {
      done(err, user);
    });
  });



router.post('/login', 
(req,res,next)=>{
passport.authenticate('local', { successRedirect: '/admin',
failureRedirect: '/login',
failureFlash: 'Invalid username or password.'}

)(req,res,next)}


)

  

Here is my question:

As you see user will be redirected to admin page only if the .user exists in the req. So can a hacker add an empty .user to the request and access my admin page?

Its kind of weird question tho. Is there any better way to do this? Thanks in advance :)


Solution

  • End-user(in your case hacker) can add any type of data to any request. So yes, end-user can modify requests to send req.user within it. However, they won't be able to access the data within it and their request will not be accepted on your "admin" endpoint if you use req.isAuthenticated().

    This is because passport JS serialises the user and stores the information in session after encryption. So UNLESS the end-user (Hacker) has access to another user's machine and copies all the session details (Browser's don't allow other sites to access another sites session) from their browser and use it, they won't be able to use admin.

    TLDR;

    No they wont be able to access "admin" endpoint by simply adding req.user in their request.