PassportJS serializeUser and deserializeUser execution flow

后端 未结 3 1454
闹比i
闹比i 2020-12-23 13:01

I\'m using passportJS with express to authenticate user by local strategy. I have seen few articles regarding how passport is setup and the execution flow. Although most of

3条回答
  •  别那么骄傲
    2020-12-23 13:26

    Since you are using PassportJS so i assume you must be having some idea about how it works. So i would add further information which i think would clear your doubt.

    Passport configuration involves three pieces:

    1. Authentication strategies
    2. Application middleware
    3. Sessions

    The answer to your question lies in 3rd piece, sessions.

    If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser. Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

    According to your implementation only the user ID is serialized to the session, keeping the amount of data stored within the session small. When subsequent requests are received, this ID is used to find the user, which will be restored to req.user

    In passports we are given option to write our own serialization and deserialization logic so that we can choose any appropriate database and not tied with strict rules.

    So to summarise, after successful authentication, user object is serialised and stored in session, if you call req.user, then you would be able to retrieve the same user object.

提交回复
热议问题