Have you noticed that after logging in or connecting to Facebook through the browser, they are not inclined to allow it again until we log out? Here a unique token is generated immediately after registration/login and stored in the local memory of our browser. This token is used for authentication and authorization processes. In this article we discuss the authentication, authorization and implementation in the Express application with JWT.

So we discussed the issue of the badge. This token contains information about our account, and you must send it with any request that requires permission.

Most of this process is coded in the back. We can experience this in the following phases.

What is authentication and authorization?

Authentication confirms that it’s the person who’s saying it. Authorization gives users access to the content.

Let’s explain it with a real example. Suppose you go on Facebook. The login page appears first, so you can enter your email address and password for authentication. After verification, you can open your friends list, your settings, your profile, etc. But others don’t have access to it. So this is the right you get after authentication, which is called authorization.

As developers, we now need to understand what happens on the programming side during authentication and authorization.

When we create a Facebook account, it generates a token with our basic information. This will be the rule shown below.

eyJhbGciOiJIUzI1NiInR5cI6IkpXVCJ9.eyJfaWQiOi1ZjZkZGRhZmFmMjU3ZTJJm0ZmQzMDciLCJ1c2VyVHlwZSI6ImN1c3RvbWyiiiwiaWF0IjoxNyAxMDM1Nyk2LCJleHAiOjE2MDE4OTk2OTZ9.THThP93-fpg6Es4OI–6YtnN-nJGUVFHKez-Ka-GP-M.

This line is sent to our browser and stored in local memory or in a cookie. Okay, authentication is complete.

We are now trying to access our configuration page. However, Facebook must approve the fact that it is the same person who has previously logged in to show you the page.

Here the browser sends a token with the settings request page to the backend.

From there, the Facebook backend deciphers the token and finds information about the user. If it is the same person, the request can be processed and the reply sent. Otherwise, it’s an error.

We implement the authentication and authorization in the Express application with JWT in the same way.

What is JWT?

So we discussed what authorisation and authentication are. But what is JWT’s role in this?

JSON Web Tokens or JWT is a set for creating encrypted access tokens using user data and some secret keys. It can also decipher and sort the user’s data.

How do I set up authentication and authorization at Express.js using JWT?

Authentication and authorization processes are performed internally. In this article we will use the Express backend to configure the authentication and authorization with JWT.

We create a simple express backend with the user schedule, create a case, login and profile path for the users.

We will set the code to register new users, login and find a way to update the profile of the authorized JWT user.

1. Implementation of MongoDB, creation of a compass and a database

In this project we use MongoDB for data storage, so it has to be installed in our system.

For the graphical management of MongoDB databases you can also install MongoDB Compass.

Then create a database and a collection for our project.

The next steps will help us get there.

1.1 Installing MongoDB

To install MongoDB on Windows 10, refer to the MongoDB for Windows 10 Installation Guide. If you use a different operating system, please read the official documentation Installation of MongoDB.

After starting MongoDB we see the screen as shown below.

1.2 Installation of the MonoDBcompass

MongoDB stores the data in the form of documents. To visualize and edit this data, we can use a graphical interface tool for MongoDB, namely the MongoDB compass.

You can go to the official website to install the MongoDB compass.

After installation, the screen will open as shown below.

Just continue with the default option. It is connected to the MongoDB running on our local system on port 27017.

Create a new database with simplebackend users and the name of the collection.

2. Create the Express.js project

We can easily build an express.js application from scratch with npm. Follow these steps.

2.1 Installation of Nodes

The installation of Nodejs on our system may differ from the operating system.

  • Macro and Windows users, use the link below to download the Nodejs installation file.

https://nodejs.org/en/download/

  • For Ubuntu users Nodejs can be installed with the following commands.

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash –
sudo apt – get installation -y nodejs

  • For other operating systems you can find the installation manual by clicking on the following link.

https://nodejs.org/en/download/package-manager/

2.2 Global node installation

Nodemon is a tool that helps you develop node applications by automatically restarting the application when folder changes are detected.

npm i-g modem

2.3 Creating a project folder

Create a project folder and navigate to it with our command line / terminal.

mkdir express backend
cd express backend

2.4 Initialization of the project node.js

To work with Node.js projects, you need a package.json file in our projects folder. So we need to initialize the Node.js project with the following command.

per minute

2.5 Installation of required packages

We now need to install the necessary express, corset, bodyguard and Morgan packages as part of our project.

npm i express cors body parser morgan

3. Main file setting (index.js)

So we launched the express.js project. We can open it now with the code editor. I’m using Visual Studio code.

The picture above shows the file structure of our urgent request.

Now start the project by creating the index.js file and importing all previously installed packages. Also identify the port number to run the application.

const express = require(express);
const app = express();
const cors = require(cors);
const bodyParser = require(body-parser);
const loger = require(morgan);
const mongoose = require(mongoose);
const port = process.env.PORT |||| 3001 ;

app.use(loger(dev)) ;

We use MongoDB as a database, so the database details need to be added to index.js.

let dbUrl = mongodb://localhost:27017/simplebackend;
var options = {
keepAlive: 1,
connectTimeoutMS: 30000,
useNewUrlParser: true,
useUnifiedTopology: true,
} ;

mongoose.connect(dbUrl, options, (err) => {
if (err) console.log(err);
}) ;

Use the packages we have imported before. I’m not here to explain the obligations of these packages. If you really want to know, read the article How to create a simple REST API with a node/expression.

app.use(cors()) ;
app.use(bodyParser.urlencoded({ extended : true }) ;
app.use(bodyParser.json()) ;
app.use(/users, users) ;
app.listen(port, function() {
console.log(running on + port) ;
}) ;

module.export = Application

So the complete index.js file looks like the one below.

4. Creating a personalised plan

Now create a template folder and add the file User.js for the custom scheme. In this file we will also add the generatePasswordHash function and the validatePassword function for authentication.

  • The generatePasswordHash function creates a hash password using the password we add when registering the account.
  • With the function validatePassword the password is hashed and compared with the password stored in the database when logging in.

We also add three fields that are completed, returned and public.

  • The retrievable table contains schematic fields that can be filled in directly from the parameters in the query-body.
  • The return table contains the fields in the diagram that must be included in the answer.

So the complete User.js file looks like this

In the templates folder we also add the file index.js to make it easier to import templates into other files.

const User = required(./user);
Module.export = {
User,
} ;

5. Creation of a configuration file

We now want to create a config.js file in the root directory to store secret keys and confidential information.

We use it to store a secret key that is used here to create an encrypted JWT token. This secret value must not be lost. Because it is necessary to decipher these tokens.

6. Creating a route

When the API is called from the external interface, it first goes to index.js, and from there it is forwarded to the routing folder.

6.1 index.js

We start by creating an index.js file in the route/user folder for your convenience. All URLs of the APIs for users are accessible here first. It is then passed to the URL path.

6.2 .js registry

In this article we discuss authentication and authorization. The registration phase is therefore very important.

After registration, the request is sent to the router register. From there, a new user is created and the user’s document is sent as a reply. In response, it adds the token generated by JWT.

The following code does the job. It takes the user ID, the secret key, the expiration date and returns the hash token. This token is activated in response to the recording.

Here I used 10d as the expiration date of the token, which expires in 10 days. But don’t worry, it will automatically update itself when it expires.

user.token = jwt.sign (
{
_id : user._id,
},
config.secret,
{
expiresIn : 10d,
}
) ;

So the complete register.js file looks like this.

If you answer, you don’t need a hasht password. We have already announced a number of custom fields that can be returned in the user’s template. In this way the fields in User.returnable are returned with a single answer.

6.3 requests.js

The same procedure shall be followed for registration. It finds a user document with an e-mail in the body. If the password in the body is correct, it returns the user data.

But the front also wants a token with an answer to the authorisation process. So we make a badge here, just like in the registration phase.

The full login.js file looks exactly like the one below.

Okay, authentication is complete. We can now proceed to the authorisation section.

6.4 profile.js

The profile route contains 3 URL-APIs, which I have explained below.

1. GET /public/:userId

This API accepts userId as a req parameter and returns the user profile data to the public. We have already implemented User.publicReturnable. These fields will be returned with a response.

Everyone has access to this API. However, we will not receive certain information, such as the user’s e-mail.

router.get(/public/:userId, async (req, res) => {
try {
let user = wait models.user.findOne({
_id: req.params.userId,
});
res.status(200).json({
data: _.pick(user, models).publicReturnable),
});
} catch (err) {
console.log(err);
res.status(400).json({
message: any error,
err,
});
}).
}) ;

2. GET /

This API returns user data with fields in User.returnable. The user has access to his own data. Guests don’t even have access to the API.

We’re adding jwtauth middleware on this road. He’s making that limitation. It is checked whether the request contains access x and whether this access is valid or not. If valid, it finds the user logged in to the token and adds data to the requesting user.

This process is called authorisation.

So, from the API, we will find a user with _id, req.user._id and respond with this data.

router.get(/, [jwtauth], async (req, res) => {
try {
let user = wait models.findOne({
_id : req.user._id,
}) ;
res.status(200).json({
data : _.pick(user, models.user.returnable),
});
} catch (err) {
console.log(err);
res.status(400).json({
message: an error has occurred,
err,
});
}.
}) ;

3. PUT /

The authorisation processes mentioned above also apply to this API. The user can only change his data, and guests do not even have access to it.

router.put(/, [jwtauth], async (req, res) => {
try {
let user = wait models.findOne({
_id : req.user._id,
}) ;
user = _.merge(user, _.pick(req.body, models.user.fillable))) ;
user = wait user.save() ;
user = _.pick(user, models.user.returnable);
res.status(200).json({
data: _.pick(user, models.user.returnable),
});
} catch (err) {
res.status(400).json({
message: an error has occurred,
err,
});
}
}) ;

The complete profile therefore looks exactly like the one shown below.

7. JWTToken authentication settings

This is one of the important steps in this article. Here we check the JWT token sent to the header with the name x-access token.

So create a directory named lib and a file named jwtlib.js. It contains the code as shown below.

In the end, the structure of our project file will therefore look exactly the same as below.

8. APITests

Our Backend Express is now ready for authentication and authorization. We can test these APIs now.

We can use the Factor tool to test the API.

8.1 Statement

We can apply to MAIL at http://localhost:3001/users/register to register a new user. Here I use the body parameters below.

{\an5} Syamlal, e-mail: [Secure via e-mail], password: password}.

This will register a new user and send a response from the backend, as shown below, back to the single token.

{Data
: {
_id: 5f7c27291f11b52378a53630, name
: Syamlal, e-mail
: [protected by e-mail],
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOi1ZjdjdjMjcyOTFmTFiNTIzNzhNTM2MzAiLCJpYXQiOjE2MDE5NzIwMDksImV4cI6MTYwMjgzNjAwOX0.0N7Y5iDMW_prDOq5Q-THJz5kpCKM4fgnT8DPmznrdt0
}.
}
.

8.2 Input

We may submit a request to MAIL at http://localhost:3001/users/login to login to your account. The following parameters are required.

{
E-mail : [Secure Email], password
: Password
}

The answer will be the same as below.

[Status: 200, data]. {_id : 5f7c26fc16401b3aa425ae6b, name : Syamlal, e-mail: [protected email], token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOi1ZjdjMjZmYzE2NDAxYjNhYTQyNWFlNmIiLCJpYXQiOjE2MDE5OTI3NzUImV4cCI6MTYwMjg1Njc3NX0.HluWGj_q7Ypn6uWcGtS2RW-RU1PNFzF0A3ssX6r6xUo}.} https://i0.wp.com/www.techomoro.com/wp-content/uploads/2020/10/login.jpg?resize=640%2C341&ssl=1.

8.3 Restoration of public profile data

Profile data for the public can be accessed via the API URL http://localhost:3001/users/profile/public/5f7c26fc16401b3aa425ae6b, where 5f7c26fc16401b3aa425ae6b is the user ID.

No tokens are required for this data.

8.4 Collection of user profile data

Here the user needs almost all data, including e-mail. The user must therefore log in with a token before he can access this API. You can use any name to send this token as header, but the name must be the same in jwtlib.js in step 7. Here I use the name x-access token.

So here we will make a GET request to the API URL http://localhost:3001/users/profile/. But keep in mind that this requirement requires that access x is entered into the header.

The x-access-attack is actually a JWT token that we receive from the answer and the login of the registry.

8.5. Updating user data

This API also requires a token for authentication. Because the user can only update his data.

Here, I’m updating Xiamlal’s name to Robin.

Here I also enabled the x-access token header for user authentication.

GitHub

The entire project we created here has been uploaded to GitHub for reference.

https://github.com/techomoro/AuthenticationAndAuthorizationExpressJWT

Good code!

Summary

In this article we learned the steps to implement authentication and authorization in the Express application with JWT. We started by making a simple express project. Routes for maintaining user profiles are created. We have added a middleware called jwtauth to restrict access to some URL APIs. We have also tested these APIs with the Postman tool.

Here we go:

Like the download…

You might like this.

express jwt passport,express-jwt typescript,express-jwt-permissions,express jwt refresh token,express-jwt-authz,express-jwt graphql,jwt authentication node js and mysql,table access in node js,passport and jwt,node express mysql mvc,passport js sequelize,nodejs mysql skeleton,node js mongodb user registration,secure rest api with jwt nodejs,nodejs res token,jwt implementation express,jsonwebtoken nodejs example,jwt medium,jwt authentication node js angular,passport js jwt example,jwt res cookie,node js login tutorial,express js android app,disadvantages of express js,benefits of express js,disadvantages of mean stack,advantages of node js over java,should i use express js,jwt redis nodejs,express-jwt vs jsonwebtoken,nodejs authentication,passport-jwt,jwt authentication,bcryptjs,nodejs jsonwebtoken example,njwt,jwt-simple,jwt refresh token implementation,invalid expiresin option for string payload,node js api key authentication,how do web tokens work,php token authentication tutorial,persistent authentication token,stateless token based authentication,token based authentication in node js mysql,jwt authentication & authorization in nodejs/express & mongodb rest apis(2019),nodejs authentication with password and jwt in express,express-jwt example,express-jwt tutorial,token based authentication in node js,express-jwt npm,express-jwt algorithms should be set

You May Also Like

10 Perfect Tech Gift Ideas For Smart Homeowners

Digitization is a trend today and many people like to wear it…

Seaborn Version 0.11.0 is here with displot, histplot and ecdfplot

Select version 0.11 here Seaborn, one of the data libraries on Python,…

Best affordable tablets you can buy in Black Friday 2020

Facebook Twitter interest Reddit Messenger WhatsApp Tablets are a commercially available gadget…

15 Best N64 Games you Need to Try on Retropie (with links) –

You have Raspberry Pi with Retropy or another system and are looking…