Authentication with a passport. Can I trust that req.user is really a registered user?

I use passport to authenticate users on my site. Users can register orders that have foreignKey (ObjectId) for the User object.

Example objects (written as mongoose schemes):

var orderSchema = new mongoose.Schema({ ... address: String, _userID: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'} }); var userSchema = new mongoose.Schema({ email: String, }); 

Mongoose will create a primary key for each object.

My question is: is it enough to check if req.user._id === order._userID ? Or can the req.user object be modified? Can I trust that req.user._id is the id registered user?

I found a couple of good resources, but this is not quite what I am asking for.

0
source share
1 answer

So the question is:

can a req.user object be faked?

It’s hard to answer, since you may have code inside your application that will have access to and inside your request object, change user . It is important to understand what code you use in the stream of each request for someone really, but especially those who are concerned about the security of their application. With that said, I can at least tell you where in the code that is installed, and you can trace it with a debugger to make sure the stream.

As you already mentioned, the passport documentation discusses the authentication configuration parameters in their manual , and by default the user's “login” will be processed when your strategy dictates successful authentication. You can also provide a custom callback (mentioned in the above documentation) to handle it. In the end, it is important that req.logIn called (which runs by default without any custom callbacks). Here is a link to the source . (The passport extends the request object through this code to provide auxiliary functions that it uses later).

The specific line that you might be interested in is here , which assigns the user property with the value authenticated user to the req object:

 this[property] = user; 

From there you have access to the registered user under req.user , and their identifier under req.user.id Please note again that this logIn function should be called only when the passport strategy indicates that a successful authentication has occurred. But in this way, the passport provided you with the ability to easily authenticate the user, and then access this user through the request object.

+3
source

Source: https://habr.com/ru/post/972004/


All Articles