Node.js use passport with LocalStrategy in Authentication Part 2
Custom callback for passport.authenticate
In previous post (part 1), the passport module has default response. Now, this post will show how to override the default response. Instead of redirecting to other routes, we can send the client back the result immediately. It is useful in Backend API service design.
We override passport module default callback by providing our callback function as the 3rd argument in the function passport.authenticate(). If we move the mouse pointer to hover the name of function authenticate(), it will pull up a description about this function (I use Visual Studio Code). This description comes from the source code of passport module. We could provide our callback to override the default manner in authentication. It also provides an example of applying the custom callback.
![]() |
The arguments of the callback function (err, user, info, status) is referring to the arguments we passed to cb function of Strategy verify function.
Now we test it with Postman. We pass a string of "intend error" as 1st argument of the cb function in Strategy verify function if the password is not match. Now the postman only receive the same message as we code our callback function as the 3rd argument in passport.authenticate().
If we post the correct username and password, the server return the username to us instead of the message in GET /secrets route. This means the passport will no longer redirect to another route as we stated in the 2nd argument of passport.authenticate() function. It is because we override the default callback function.
We can call res.redirect() function to redirect another route if need.

We can now redirect other routes if login fails or error occurs in the Strategy verify function.
Now, we can handle how server respond for all situation in authentication with the custom callback.
The source code(v1.2) of this part is uploaded to github.
Next part, we will add Session so that the server can remember the client. You can find the function of Session in post Cookie and Session.




Comments
Post a Comment