Handling Authentication in NodeJS (Express) with Passport Part 2 — MongoDB and Passport
So far, we’ve created our project boilerplate to make development easier for us. In this part, we’ll set up our database and create an authentication and authorization system.
We’ll be setting up a MongoDB database using the popular Mongoose ORM. First, let’s install the dependency:
npm i mongoose bcrypt jsonwebtoken validator
We’ll need each of those packages for various things while we manage entries in our database. Bcrypt is useful for hashing passwords, JSON Web Tokens are will serve as our means of authentication when communicating with the server and validator will be used for validating data to be saved to our database.
Creating a Mongoose connection
First, in your .env file, add a new key titled DEV_DB. This will serve as our MongoDB database name. MongoDB databases use the MongoDB protocol, so a to create a database named ‘passport_auth_dev’, your DEV_DB value will look somewhat like this:
In the db folder, create a mongoose.js file, and set up a mongoose connection so:
Import your mongoose file into your index.js and restart your app, you’ll know if your database is successfully created via the message on your console.
Creating a collection schema
We’ll only be creating a User collection in this project with 3 fields: email, userName and password.
In the model folder, create a user.model.js file and update it with this code:
You’ll need to update your .env file with three more keys:
- A HASH key to indicate how much time bcrypt should take while creating a hash. A higher number makes increases the security of your passwords but can adversely affect your server response time. 10 is acceptable.
- JWT_PUBLIC_SECRET and JWT_PRIVATE_SECRET: There are different algorithms for generating JWTs, I’m using the RS256, which may be a bit more complicated as it requires a private and public RSA key pair (Note which key is public and which is private). You can generate a key pair here. Copy both keys to an editor, e.g., VSCode, Use the find and replace( ctrl+F) functionality to replace ALL newline characters( ctrl+Enter in VSCode )with \n, and assign to the correct JWT key.
We’re ready to integrate PassportJS into our app. But first, some more dependencies:
npm i passport passport-jwt passport-local
Now, let’s get started.
In the services folder, let’s create a subfolder named passport. This subfolder should have two files: passport-local.js and config.js. The first file handles our signup and login functionalities while the second contains the settings for retrieving and decoding our JWT.
You can set a ‘username’ and ‘password’ field if yours, for some reason, won’t be the same as the default. Our ‘username’ field is the ‘email’ in our request body. Our users can sign in via userName or email, so while the ‘username’ field remains ‘email’, we can configure our passport-local strategy to look through both fields in our database for the user’s data.
Passport error callbacks have 3 arguments, the third of which is the ‘info’. This is an object which can transfer information such as status code or error messages to the next middleware in the stack or to your error handler.
Passport provides us with a number of ways to extract JWTs from request headers, in this case, we combine two different ways — ExtractJWT.fromAuthHeaderAsBearerToken() which extracts the token when it's prefixed with ‘Bearer ’(note the space), and a custom Cookie Extractor function which extracts the token from a named token. You can check out other ways of extracting tokens in the passport-jwt documentation.
The cookie is parsed by the cookie-parser package, hence it should be added to the express middleware stack. You should also initialize Passport in the app.js file so your app.js should look like this now:
We are yet to check if our configuration works and we’ll complete the Passport local strategy in the next article by creating our authentication middleware, controllers and routes.
Handling Authentication in NodeJS (Express) with Passport Part 2 — MongoDB and Passport was originally published in codeburst on Medium, where people are continuing the conversation by highlighting and responding to this story.