This example illustrates how to use Express 4.x and Passport to sign users in with a username and password. Use this example as a starting point for your own web applications.
To get started with this example, clone the repository and install the dependencies.
$ git clone https://github.com/passport/express-4.x-local-example.git
$ cd express-4.x-local-example
$ npm install
Start the server.
$ npm start
Navigate to http://localhost:3000
.
This example illustrates how to use Passport and
the passport-local
strategy within an Express application to sign users in
with a username and password.
The example builds upon the scaffolding created by Express generator, and uses EJS as a view engine and plain CSS for styling. This scaffolding was generated by executing:
$ express --view ejs express-4.x-local-example
The example uses SQLite for storing user accounts. SQLite is a lightweight database that works well for development, including this example.
Added to the scaffolding are files which add authentication to the application.
-
This file initializes the database by creating the tables used to store user accounts and credentials.
-
This file initializes Passport. It configures the password strategy with a
verify
callback. The callback verifies the password by finding the user account in the database. If the account is found, the callback hashes the password entered and compares it to the hashed password stored in the database. If the comparison is equal, the user is authenticated.This file also supplies the serialization functions used for session management.
-
This file defines the routes used for authentication. In particular, there are two routes used to authenticate with a username and password:
-
GET /login
This route renders a page that prompts the user to enter their username and password.
-
POST /login/password
This route authenticates the user using their username and password.
-
-
This file defines the routes used for registration. In particular, there are two routes used to create an account:
-
GET /users/new
This route renders a page that prompts the user to enter the information needed to register an acccount. This information consists of their name, preferred username, and password.
-
POST /users
This route creates a new account using the information entered by the user. The password is first hashed and stored in hashed format.
-