User Authentication
and Authorization
WIF2003 WEB PROGRAMMING
Objectives
User Authentication & Authorization
JSON Web Token (JWT)
Bcrypt
Cookie parser
User Authentication &
Authorization
Securing web applications
In application security, there are two crucial
concepts that work together to secure access
to web applications:
Authentication
Authorization
What is User Authentication &
Authorization?
Authentication Authorization
The process of verifying a The process of authorizing or
user's or an entity's identity refusing access to particular
resources or functions within
This include validating the
an application
user's credentials, such as
username and password Once a user has been
when user login to a web verified as authentic, the
application program checks their level
of authorization to decide
which areas of the
application they can access
JSON Web Token (JWT)
JSON Web Token (JWT) authentication is a
popular method for securing web applications,
Can be implemented in a MERN (MongoDB,
Express.js, React, Node.js) Stack application
The basic idea is to:
generate a token on the server,
send it to the client upon successful authentication,
include this token in subsequent requests to
authenticate the user
Website: https://jwt.io/
How JSON web token (JWT)
Authentication works?
CLIENT SERVER
1 POST /login (email, password) 2 If user && password valid,
Create unique JWT
LOGIN
HTTPS
4
Store JWT
(cookie or 3
JWT
localStorage)
5 GET /someProtectedRoute
JWT
6 If valid JWT,
ACCESS
HTTPS Allow access
Protected data
7
Bcrypt
– hashing passwords securely
Why not MD5, SHA1, SHA2, SHA3?
They are general purpose hash functions
Bcrypt is a library to help us hash passwords
A password-hashing function uses a variant of the
Blowfish encryption algorithm’s keying schedule
Introduce a work factor, which allows you to determine
how expensive the hash function will be
For more details:
https://en.wikipedia.org/wiki/Bcrypt
https://codahale.com/how-to-safely-store-a-password/
https://www.npmjs.com/package/bcryptjs
Cookie
A cookie is a piece of data that
Is sent to the client-side with a request, and
is stored on the client-side itself by the Web Browser the
user is currently using
With the help of cookies –
It is easy for websites to remember the user’s
information
It is easy to capture the user’s browsing history
It is also useful in storing the user’s sessions
Cookie parser
To make use of cookies in our web applications,
cookie-parser middleware is used for handling HTTP
cookies in Node.js
Cookie parser typically performs the following tasks:
Extract the cookie data from the HTTP request and convert
it into a usable format that can be accessed by the server-
side code
Parse the cookie data to extract individual values such as
the cookie name, value, and expiration date
Website: https://www.npmjs.com/package/cookie-
parser
Node.js and Express.js
Installation and Configuration
Create Project folders
Create a new project folder (e.g.
USER_AUTHENTICATION)
Inside your project folder create two directories
named:
backend
frontend
Separate the backend and frontend codes
Setup backend: Web server
Inside the backend directory:
Create new package.json file:
$ npm init –y
-y : set the default value for all information
Create a new main script file
You can give any name such as index.js, server.js, app.js
$ fsutil file createnew index.js 0
Setup backend: Web server
(cont.)
Install all packages needed by backend:
express
mongoose
nodemon
dotenv
jsonwebtoken
Bcryptjs
cookie-parser
CORS
$ npm install express mongoose cors bcryptjs
cookie-parser nodemon jsonwebtoken mongoose
dotenv
Package Dependencies (1)
JS Package Description
express A fast and minimalist web framework for Node.js.
mongoose A JS object-oriented programming library that creates
a connection between MongoDB and Node.js
nodemon Nodemon automatically restarts the node application
when file changes in the directory are detected.
jsonwebtoken • An authentication way for creating data with
optional signature and/or optional encryption.
• A library for creating and verifying JSON Web
Tokens (JWTs) used for authentication.
bcryptjs A library to help you hash passwords.
Package Dependencies (2)
JS Package Description
cors • A middleware used to enable Cross-Origin Resource
Sharing (CORS) for an Express.js application.
• Allowing or blocking web page access to resources
on a different domain.
dotenv • Allow you to store configuration data in a .env file,
which is typically not committed to version control, to
separate sensitive information from your codebase
• This file contains key-value pairs that represent the
environment variables.
cookie- • Middleware that handles cookie-based sessions in
parser incoming HTTP requests
• Extract information from cookies that may be
required for authentication or other purposes.
Setup backend : Web server
(cont.)
Edit main script file, server.js to:
Requireexpress and define a variable app to
execute express as a function
Define app.listen to start the server at a
particular port
Define a basic root route that respond with
“Hello World" when a GET request is made to
the homepage
Setup backend : Web server
(cont.)
const express = require('express');
const app = express();
const PORT = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(PORT, () => {
console.log(`Server has started on port
${PORT}!`)
})
Setup backend : Web server
(cont.)
Edit package.json file to:
create a script for nodemon command to restart
server automatically when if there are any
changes in our script
"scripts": {
"server": "nodemon index.js"
},
To start the nodemon, execute this command at terminal:
npm run server
Setup database:
MongoDB
Assumption: You have successfully installed mongodb on your
computer.
MongoDB compass &
MongoDB Atlast
To setup MongoDB Compass after installing
MongoDB, you may refer to this:
https://www.geeksforgeeks.org/create-database-
using-mongodb-compass/
To setup Cloud Hosted Database, MongoDB
Atlas and link the database to your backend
Register account or login using your Google / Github
account:
https://www.mongodb.com/cloud/atlas/register
Follow the procedures to setup your database in the
next few slides
STEP 1: Go into your MongoDB
cloud clusters
STEP 2: Click on the ‘Database’
Access (left of the sidebar)
Click on ADD NEW DATABASE USER
Steps 3 - 5
STEP 3: Fill out the Password Authentication with your desired
username and password for the database of this particular
project.
STEP 4: Before saving this, click the Built-in Role dropdown,
and select Read and write to any database. Now, go ahead
to click Add user.
STEP 5: Click on Database, and on the left side of the sidebar,
click the connect button, which is beside View Monitoring.
A modal popup will be displayed, then click connect your
application and copy the code snippet you find there.
Connect your
application: Drivers
Replace <username>
(yinkia) & <password>
with the username
and password you
created in STEP 3 in
your index.js file in the
backend folder.
Create .env file
Create a .env file in your ‘backend’ directory, which
will contain your MONGODB_URL, PORT,
database_name, and database_password like the
code below:
MONGO_URL =
"mongodb+srv://yinkia:<password>@cluster0.bm7jbbf.mongo
db.net/?retryWrites=true&w=majority&appName=Cluster0";
PORT = 3000;
Replace MONGO_URL with your MongoDB Atlas’s
connection URL
Add connection to the MongoDB
database
Update main index.js file to add connection to
the MongoDB
Configuring the web application to be able to
have access to the .env file:
You can get the information in your .env file by doing
process.env
Add CORS
(Cross origin resource sharing)
Update main index.js file to:
Use the cors() express middleware function to allow
requests from other domains to access the resources
on your server
The CORS headers that your server should include in
the response can be specified using the function's
optional configuration object parameter:
origin,
methods, and
credentials
Index.js file (Part 1)
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
require("dotenv").config();
const { MONGO_URL, PORT } = process.env;
Index.js file (Part 2)
// Establish the MongoDB connection
mongoose.connect(dbUrl)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error.message);
// Handle specific error conditions
if (error.name === 'MongoNetworkError') {
console.error('Network error occurred. Check your MongoDB
server.');
} else if (error.name === 'MongooseServerSelectionError') {
console.error('Server selection error. Ensure'
+ ' MongoDB is running and accessible.');
} else {
// Handle other types of errors
console.error('An unexpected error occurred:', error);
}
});
Index.js file (Part 3)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Server has started on port ${port}!`)
})
Index.js file (Part 4)
// Use the cors() express middleware function
app.use(
cors({
origin: ["http://localhost:4000"],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
})
);
//The express. json() function is a middleware function
//parse incoming JSON data from HTTP requests
app.use(express.json());
Implement backend
Refer to sample codes in references
Create folders
Create the following folders in the backend
directory of your application:
Controllers
Middlewares
Routes
Models
util
Implement the Backend
Implement the backend for authentication and
authorization:
Handle the SIGNUP Route
Handle the LOGIN Route
Handle the HOME Route
Implement the Frontend
Create a new react application
In the terminal, move to frontend folder and
create a New React Application using this
command:
$ npx create-react-app
After the command above has successfully
created the app, type in your terminal to start
the New React Application:
$ npm start
Start the new react application
(npm start)
Remove some boilerplate in the
React application
Restart your React application
(npm start)
Implement the Frontend
Implement the backend for authentication and
authorization:
Handle the Signup Logic
Handle the Login Logic
Handle the Home Page Logic
References
https://www.freecodecamp.org/news/how-to-
secure-your-mern-stack-application/
https://medium.com/@sanikakotgire2003/jwt-
json-web-token-authentication-using-mern-
stack-2ea59127d37d