Node.js use passport with LocalStrategy in Authentication Part 5
Establish a session with custom callback of passport.authenticate()
In post part 2, we have provide custom callback function into passport.authenticate() function. As the description of authenticate() function stated, we have to establish a session by ourself. This post demonstrate to establish a session.
We modify the code(v1.2) in part 2. First, import and setup session.
Second, assign the argument user to a property user of an object and pass this object of req.session[passport] inside the body of custom callback. We imitate what the default manner of passport done to save user data into Session. Then we check the content of req.session and req.isAuthenticate() in the GET /secrets route.
Now we test with Postman. It received error message "Fail to deserialize user out of session". Same error message also printed on the terminal.
Then we add the passport.deserializeUser() method at the end of file.We use Postman to test again. Now it get /secrets message. The terminal of server shows the content of req.session before we assign user to it and after redirect to "/secrets". We also note that the result of req.isAuthenticated() is true. Therefore, we now can use req.isAuthenticated() to restrict client access like part 3.
For additional test, if we change the property name assigned to req.session["passport"], the result of req.isAuthenticated() becomes false.
We change back the property name assigned to req.session["passport"]. The next thing is to pass the user information stored in session to req.user when the client access the api service. We add a line console.log(req.user) inside GET /secrets route to see the content.
Use postman to login and we see there is user information in req.user. Passport has retrieved the content of user in Session and passed it to req.user automatically as default manner.
By assigning the user information to Session in the format of Passport default way in our custom callback function, Passport will operate normally as using the default manner of default callback. The code(v2.4) used in this post is uploaded to github.






Comments
Post a Comment