Local Authentication Using Passport in Node.js

Local Authentication Using Passport in Node.js

In Passport Authentication for Node.js Applications, we talked about authentication using Passport as it relates to social login (Google, Facebook, GitHub, etc.). In this article, we’ll see how we can use Passport for local authentication with a MongoDB back end.

[…]

Next, we’ll need a form with username and password inputs as well as a Submit button. Let’s do that! Create a file called auth.html in the root folder of your app, with the following contents:

[…]

Here, we require passport and initialize it along with its session authentication middleware, directly inside our Express app. Then, we set up the '/success' and '/error' routes which will render a message telling us how the authentication went. If it succeeds, we’re going to show the username parameter, which we’ll pass to the request. We’re using the same syntax for our last route, only this time instead of using [res.SendFile()](http://expressjs.com/en/api.html#res.sendFile) we’re using [res.send()](http://expressjs.com/en/api.html#res.send), which will render the given string as text/html on the browser. Then we’re using serializeUser and deserializeUser callbacks. The first one will be invoked on authentication, and its job is to serialize the user instance with the information we pass to it (the user ID in this case) and store it in the session via a cookie. The second one will be invoked every subsequent request to deserialize the instance, providing it the unique cookie identifier as a “credential”. You can read more about that in the Passprot documentation.

[…]