Authentication with passport. Can I trust that req.user is indeed the logged in user?

我与影子孤独终老i 提交于 2019-12-23 05:23:05

问题


I'm using passport to authenticate users at my site. Users can register orders, which have and foreignKey (ObjectId) to the User object.

Example-objects (written as mongoose schemas):

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 the 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 tampered with? Can I trust that req.user._id is the id of the logged in user?

I've found a couple of good resources, but it's not exactly what I'm asking of.

  • http://toon.io/articles/understanding-passportjs-authentication-flow/
  • http://passportjs.org/guide/authenticate/

回答1:


So the question:

can the req.user object be tampered with?

Is difficult to answer, since you could have code within your application that will have access to your request object, and within it, modify the user. It's important to understand what code you have running within the flow of each request for anyone really, but especially those concerned about the security of their application. With that said, I can at least point you to where in the code this is established, and you can trace it with a debugger to assure yourself of the flow.

As you've mentioned, the passport documentation discusses authentication configuration options in their guide, and by default will process "logging in" the user when your strategy dictates successful authentication. You can provide a custom callback (mentioned in the referenced documentation above) to process this as well. In the end, it's important that req.logIn is called (which is done by default without any custom callbacks provided). Here's a link to the source. (Passport extends the request object via this code to provide helper functions which it later uses.)

The specific line you maybe interested in is here, which assigns to the req object the property user with a value of the authenticated user:

this[property] = user;

From there on, you have access to the logged in user under req.user, and their ID under req.user.id. Again note that this logIn function should only be called when the passport strategy states that successful authentication has occurred. But in this way, passport has provided you with a way of easily authenticating the user, and then getting access to this user via the request object.



来源:https://stackoverflow.com/questions/24649274/authentication-with-passport-can-i-trust-that-req-user-is-indeed-the-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!