Building APIs is important; however, building secured APIs is also very important. In this tutorial, you learn how to build a secured API in Node.js. The authentication will be handled using tokens. Let's dive in.
Let's talk a little about cookies and tokens, to understand how they work and the differences between them.
Cookie-based authentication keeps an authentication record or session both on the server and the client side. In other words, it is stateful. The server keeps track of an active session in the database, while a cookie is created on the front-end to hold a session identifier.
In token-based authentication, every server request is accompanied by a token which is used by the server to verify the authenticity of the request. The server does not keep a record of which users are logged in. Token-based authentication is stateless.
In this tutorial, you will implement token-based authentication.
First, create a folder where you will be working from, and initialize npm. You can do so by running:
npm init -y
Use the package.json file I have below. It contains all the dependencies you will be making use of to build this application.
#package.json { "name": "api-auth", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start-dev": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "bcryptjs": "^2.4.3", "body-parser": "^1.17.2", "express": "^4.15.4", "express-promise-router": "^2.0.0", "joi": "^10.6.0", "jsonwebtoken": "^8.0.0", "mongoose": "^4.11.10", "morgan": "^1.8.2", "nodemon": "^1.12.0", "passport": "^0.4.0", "passport-jwt": "^3.0.0", "passport-local": "^1.0.0" } }
Now you can install the dependencies by running:
npm install
You can go grab a cup of coffee as npm does its magic; you'll need it for this ride!
Create a new file called app.js. In this file, you will require some packages and do a bit of setup. Here is how it should look.
#app.js // 1 const express = require('express') const morgan = require('morgan') const bodyParser = require('body-parser') const mongoose = require('mongoose') const routes = require('./routes/users') // 2 mongoose.Promise = global.Promise mongoose.connect('mongodb://localhost:27017/api-auth') const app = express() // 3 app.use(morgan('dev')) app.use(bodyParser.json()) // 4 app.use('/users', routes) // 5 const port = process.env.PORT || 3000 app.listen(port) console.log(`Server listening at ${port}`)
POST /users/
signin
401 183.635 ms - -
. You also require your routes (which will be created soon) and set it to routes.It's time to get our model up and running.
Your User model will do a few things:
Time to see what that should look like in real code. Create a folder called models, and in the folder create a new file called user.js. The first thing you want to do is require the dependencies you will be making use of.
The dependencies you will need here include mongoose and bcryptjs.
You will need bcryptjs for the hashing of a user password. We will come to that, but for now just require the dependencies like so.
#models/user.js const mongoose = require('mongoose') const bcrypt = require('bcryptjs')
With that out of the way, you want to create your user schema. This is where mongoose comes in handy. Your schema will map to a MongoDB collection, defining how each document within the collection should be shaped. Here is how the schema for your current model should be structured.
#models/user.js ... const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true } })
In the above, you have just two fields: email and password. You are making both fields a type of String, and requiring them. The email also has an option of unique
, as you will not want to different users signing up with the same email, and it is also important that the email is in lowercase.
The next part of your model will handle the hashing of the user password.
#models/user.js ... userSchema.pre('save', async function (next) { try { const salt = await bcrypt.genSalt(10) const passwordhash = await bcrypt.hash(this.password, salt) this.password = passwordhash next() } catch (error) { next(error) } })
The code above makes of bcryptjs to generate a salt. You also use bcryptjs to hash the user password by passing in the user's password and the salt you just generated. The newly hashed password gets stored as the password for the user. The pre hook function ensures this happens before a new record of the user is saved to the database. When the password has been successfully hashed, control is handed to the next middleware using the next()
function, else an error is thrown.
Finally, you need to validate user password. This comes in handy when a user wants to sign in, unlike the above which happens for signing up.
In this part, you need to ensure a user who wants to sign in is rightly authenticated. So you create an instance method called isValidPassword
()
. In this method, you pass in the password the user entered and compare it with the password attributed to that user. The user is found using the email address s/he entered; you will see how this is handled soon. A new error is thrown if one is encountered.
#models/user.js ... userSchema.methods.isValidPassword = async function (newPassword) { try { return await bcrypt.compare(newPassword, this.password) } catch (error) { throw new Error(error) } } module.exports = mongoose.model('User', userSchema)
When that is all set and done, it is important you export the file as a module so it can be rightly required.
Passport provides a simple way to authenticate requests in Node.js. These requests go through what are called strategies. In this tutorial, you will implement two strategies.
Go ahead and create a file called passport.js in your working directory. Here is what mine looks like.
#passport.js // 1 const passport = require('passport') const JwtStrategy = require('passport-jwt').Strategy const { ExtractJwt } = require('passport-jwt') const LocalStrategy = require('passport-local').Strategy const { JWT_SECRET } = require('./config/index') const User = require('./models/user') // 2 passport.use(new JwtStrategy({ jwtFromRequest: ExtractJwt.fromHeader('authorization'), secretOrKey: JWT_SECRET }, async (payload, done) => { try { const user = User.findById(payload.sub) if (!user) { return done(null, false) } done(null, user) } catch(err) { done(err, false) } })) // 3 passport.use(new LocalStrategy({ usernameField: 'email' }, async (email, password, done) => { try { const user = await User.findOne({ email }) if (!user) { return done(null, false) } const isMatch = await user.isValidPassword(password) if (!isMatch) { return done(null, false) } done(null, user) } catch (error) { done(error, false) } }))
JwtStrategy
. This object receives two important arguments: secretOrKey
and jwtFromRequest
. The secretOrKey
will be the JWT secret key which you will create shortly. jwtFromRequest
defines the token that will be sent in the request. In the above, the token will be extracted from the header of the request. Next, you do a validation to look for the right user, and an error gets thrown if the user is not found.LocalStrategy
. By default, the LocalStrategy uses only the username and password parameters. Since you are making use of email, you have to set the usernameField
to email. You use the email to find the user, and when the user is found, the isValidPassword
()
function which you created in the user model gets called. This method compares the password entered with the one stored in the database. The comparison is done using the bcryptjs compared method. Errors are thrown if any is encountered, else the user is returned.Before you jump to setting your controllers and routes, you need to create the JWT secret key mentioned above. Create a new folder called config, and a file inside called index.js. You can make the file look like this.
#config/index.js module.exports = { JWT_SECRET: 'apiauthentication' }
The user controller gets called whenever a request is made to your routes. Here is how it should look.
#controllers/users.js // 1 const JWT = require('jsonwebtoken') const User = require('../models/user') const { JWT_SECRET } = require('../config/index') // 2 signToken = ((user) => { return JWT.sign({ iss: 'ApiAuth', sub: user.id, iat: new Date().getTime(), exp: new Date().setDate(new Date().getDate() + 1) }, JWT_SECRET) }) module.exports = { // 3 signup: async (req, res, next) => { console.log('UsersController.signup() called') const { email, password } = req.value.body const foundUser = await User.findOne({ email }) if (foundUser) { return res.status(403).json({ error: 'Email is already in use' }) } const newUser = new User({ email, password }) await newUser.save() const token = signToken(newUser) res.status(200).json({ token }) }, // 4 signin: async (req, res, next) => { const token = signToken(req.user) res.status(200).json({ token }) }, // 5 secret: async (req, res, next) => { res.json({ secret: "resource" }); } }
signToken
()
.signToken
()
function gets called with the new user as an argument to create a new token.signToken
()
function that creates a new token.Before you create the main routes for your application, you will first create a route helper. Go ahead and create a new folder called helpers, and a file called routeHelpers.js. Here is how it should look.
#helpers/routeHelpers.js const Joi = require('joi') module.exports = { validateBody: (schema) => { return (req, res, next) => { const result = Joi.validate(req.body, schema) if (result.error) { return res.status(400).json(result.error) } if (!req.value) { req.value = {} } req.value['body'] = result.value next() } }, schemas: { authSchema: Joi.object().keys({ email: Joi.string().email().required(), password: Joi.string().required() }) } }
Here you are validating the body of requests sent by users. This will ensure that users enter the right details when signing up or in. The details to be validated are obtained from req.body
.
The routes of your application will take this format.
#routes/users.js const express = require('express') const router = require('express-promise-router')() const passport = require('passport') const passportConf = require('../passport') const { validateBody, schemas } = require('../helpers/routeHelpers') const UsersController = require('../controllers/users') router.route('/signup') .post(validateBody(schemas.authSchema), UsersController.signup) router.route('/signin') .post(validateBody(schemas.authSchema), passport.authenticate('local', { session: false }), UsersController.signin) router.route('/secret') .get(passport.authenticate('jwt', { session: false }), UsersController.secret) module.exports = router
Save it in routes/users.js. In the above, you are authenticating each request, and then calling the respective controller action.
Now you can start up your server by running:
npm run start-dev
Open up postman and play around with your newly created API.
You can go further to integrate new features to the API. A simple Book API with CRUD actions with routes that need to be authenticated will do. In the tutorial, you learned how to build a fully fledged authenticated API.
If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato marketplace.
Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Getting Started With Django: Newly Updated Course
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…