JWT authentication in Expresswebjs
Tags: node, expresswebjs, api, microservices
Published: 2021-03-07 10:50:46

With the rising popularity of single page applications, mobile applications, and RESTful API services, the way web developers write back-end code has changed significantly. We now use [expresswebjs](https://expresswebjs.com/) to build APIs that our front-end applications consume. ExpressWebJs strives to give you the tools you need to implement authentication quickly, securely, and easily. Since ExpressWebJs does not support session state, incoming requests that you wish to authenticate will be authenticated via a stateless mechanism such as API tokens.

In this article, we will look at using JWT to secure our ExpressWebJs APIs.

## What is a JSON Web Token?

JSON Web Token (JWT) is an open standard that allows two parties to securely send data and information as JSON objects. This information can be verified and trusted because it is digitally signed.

JWT authentication has aided the wider adoption of stateless API services. It makes it convenient to authorise and verify clients accessing API resources. It is a critical part of the authentication system in javascript powered applications.

## Getting Started
The first thing we are going to do is create a new [expresswebjs](https://expresswebjs.com/) application.To start your new project, you can open your terminal or CLI and type npx expresswebcli new command, followed by your project name. Example:

```cli
  npx expresswebcli new jwtApp
```
Once that is done, cd into your project like so <code>cd jwtApp</code> and run <code>npm install</code> to install your packages.

When that is done, you can now create your .env file:
```cli
   cp example.env .env
```
In our .env we can now configure our database. ExpressWebJs supports SQL and NOSQL database. In this tutorial, we will be using Mysql which is an SQL database.

```js
APP_KEY=base64:Mk9TtGvMu3Kfp9wdahuownbdgsI3VTx2MXTQjN/6CFBadI=
APP_NAME=ExpressWebJs
APP_ENV=local
APP_HOST=127.0.0.1
APP_PORT=5000
APP_TRANSFER_PROTOCOL=http

DB_SHOULD_CONNECT=true
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_USER=
DB_PASSWORD=
DB_DATABASE=network-provider
DB_USENEWURLPARSER=true
DB_USEUNIFIEDTOPOLOGY=true
DB_USECREATEINDEX=true
```

### Note: Don't forget to set your APP_KEY.

run <code>npm run dev</code> to start your app

To generate our authentication files, we will now run auth Maker command to setup our auth routes 

```cli
  node maker make-auth
```
Our auth routes will be generated in <code>Routes/authRoute/index.js</code> file.

```js
"use strict";
const Route = require("@routerManager");

/*
|-------------------------------------------------------------
| Authentication Route File   
|-------------------------------------------------------------
|
| This route handles both login and registration.
| 
*/

Route.post("/register", "Auth/RegisterController@register");

Route.post("/login", "Auth/LoginController@login");

module.exports = Route.exec;
```

Next, uncomment the auth middleware inside the App/Http/kernel.js file routeMiddleware section:

```js
  /*
  |-----------------------------------------------------------
  | Route Middleware
  |-----------------------------------------------------------
  |
  | Route middleware is a key/value object to conditionally 
  | add middleware on
  | specific routes or assigned to group of routes.
  |
  */
  routeMiddleware: {
    auth: "App/Http/Middleware/Auth",
  },
```

At this point we need to setup and run our migration schema for our user model. Head over to Database/Migrations/20201209124747_user.js file.

```js
/**
 * Migration layout file.
 * Assign your table name to the tableName variable.
 * Remember, it's always in plural
 */
let tableName = "users";
exports.up = function (knex) {
  return knex.schema.createTable(tableName, (table) => {
    table.increments("id");
    table.string("username").notNullable();
    table.string("email").unique().notNullable();
    table.string("password", 255).notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable(tableName);
};
```

we can now run our migration with the following command:

```cli
   node maker run-sql-migration
```

To view our authentication config, head over to App/Config/auth.js file.

```js
  module.exports = {
  /*
  |-----------------------------------------------------------
  | Authenticator
  |-----------------------------------------------------------
  |
  | ExpressWebJs does not support session state, incoming 
  | requests that 
  | you wish to authenticate must be authenticated via a 
  | stateless mechanism such as API tokens.
  |
  */
  authenticator: "jwt",

  /*
  |-----------------------------------------------------------
  | Jwt
  |-----------------------------------------------------------
  |
  | The jwt authenticator works by passing a jwt token on each 
  | HTTP request
  | via HTTP `Authorization` header.
  |
  */
  jwt: {
    model: "User_model",
    driver: "jwt",
    uid: "email",
    password: "password",
    secret: process.env.APP_KEY,
    options: {
      expiresIn: 86400, //default is 86400 (24 hrs)
    },
  },
};
```
To read more about authentication config, visit [ExpressWebJs Authentication](https://expresswebjs.com/2.0/guide/security.html#password-hashing).

## Route Authentication
We can now authenticate our routes like so:
```js
  Route.get('/user', 'UserController@index',['auth']);
```

You can also authenticate your route groups like so:
```js
  Route.group('/user',['auth'],()=>{
    Route.get('/', 'UserController@index');
    Route.get('/:id', 'UserController@show');
    Route.post('/save', 'UserController@save');
    Route.patch('/update', 'UserController@update');
    Route.delete('/delete', 'UserController@destroy');
});
```
READ [developing-rest-apis-with-expresswebjs-v2](https://dev.to/alexigbokwe/developing-rest-apis-with-expresswebjs-v2-a-nodejs-framework-part-1-1fg4).

In your PostMan, access the register endpoint using a post method <code>127.0.0.1:5000/api/register</code> and input your username, email and password.

### Conclusion
Well done! You have learned how to secure your API routes with [ExpressWebjs](https://expresswebjs.com/). Need to use [ExpressWebjs](https://expresswebjs.com/) to build your API or micro-service? I'd bet on [ExpressWebjs](https://expresswebjs.com/) as the tool of choice for speed and ease of use.

I will be discussing on [ExpressWebjs Data Validation ](https://expresswebjs.com/2.0/guide/validation.html#defining-the-routes) in my next article.
You can follow me on twitter [@EmekaIgbokwe](https://twitter.com/EmekaIgbokwe)
You can follow ExpressWebJs on twitter [@expresswebjs](https://twitter.com/expresswebjs)
and don't forget to star on github [ExpressWebJs](https://github.com/Alexigbokwe/ExpressWebJs)

Please, let me know if you have any questions in the comment section. 😊