Authentication in Node.js

Authentication

What is JWT

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Prerequisites

To follow along with this tutorial, you will need:

  • A working knowledge of JavaScript.
  • A good understanding of Node.js.
  • A basic understanding of MySql or any database of your choice.
  • Postman and some knowledge on how to use Postman.

Creating our backend server

To get started, we’ll need to set up our project.

npm install express jsonwebtoken dotenv nodemon bcryptjs mysql
const express = require(“express”);const app = express();const bodyParser = require(“body-parser”);app.use(express.json());app.use(bodyParser.urlencoded({extended: true}));app.listen(5000, ()=>{console.log(“Server is listening on port 5000”);})
“start”: “nodemon server.js”,

What is MySQL

MySQL is a relational database management system based on SQL — Structured Query Language. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications.

Setting up MySql

To start using Mysql you need to download XAMMP and MySql Workbench in order to proceed with this project. You can use any other service but since we are using xammp and MySql workbench it is advised to use them with us and follow along.

Connecting MySql to Node.js

Lets move onto our code and setup a database connection.

create database testDB;
use testDB;
create table user(
id int not null auto_increment,
username varchar(250) not null,
user_password varchar(1000) not null,
primary key(id)
);
insert into user(username, user_password)
values(‘user’, ‘1234’)

Registering a User

Once database is connected and everything is working fine, lets move on to connecting postman post request and mysql using a query.

What is bcryptjs

bcryptjs is a password-hashing npm package used with node.js

Login a User

Since we were able to register a user using bcryptjs, we will be login the user with same credentials as in database. We will be creating login post route of it.

Correct credentials output

Incorrect credentials output

Using JWT

Now when our user is successfully authenticated we will be saving user data into a token using jsonwebtoken.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.