# 1. PassportJS

PassportJS is an authentication module for NodeJS which uses the standard Connect middleware structure. As a result, it is convenient to integrate with any applications that operate on the middleware structure like Express. If you haven’t known about Connect middleware yet, take a look at this post Nodejs with Express - More advanced stuff. Passport supports many authentication methods (strategies) like Local (using username and password), OAuth, OpenID or through Facebook, Google, Twitter,…

To use PassportJS, install it as a dependency for your project

Next, add this to your main app.js file. Put it after initializing session

# 2. An example with Local strategy - Authentication using Username and Password

## 2.1 Configuration

Now to use Passport, you need a strategy for instructing Passport how to authenticate. In this first example, I will use Local strategy (Username and Password authentication) provided by passport-local. Install it using npm

You need to configure to tell it how to check whether the input username and password is correct. The below code is just an example using Sequelize to select the right user from database. You can replace it with your own one to check the username and password. Remember to return done() with the right arguments for each case as shown in the example.

That’s not everything, if you are building a typical web application and you want to maintain the authentication state in session, you need to define 2 functions serializeUser and deserializeUser for serializing/deserializing user instances to and from the session

## 2.2 Build the Login form

That’s quite enough for the configuration. Now let’s build the login form. This example uses ejs view engine

And the routing for that login page

## 2.3 Middleware handler for Login

Now set up the routing and the middleware handler for login

## 2.4 Logout

To logout, simply put a hyperlink to /logout. This is the function for logging out

For some pages, you want to force the user to log in before viewing the page, you can use define a middleware that runs before the handler of that route is activated. For example

If the request can reach adminHandler, that means the user is already authenticated. Otherwise, the user would be redirected to /login.