JWT authentication in Expresswebjs
Chukwuemeka Igbokwe
Posted on March 7, 2021
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 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 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:
npx expresswebcli new jwtApp
Once that is done, cd into your project like so cd jwtApp
and run npm install
to install your packages.
When that is done, you can now create your .env file:
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.
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 npm run dev
to start your app
To generate our authentication files, we will now run auth Maker command to setup our auth routes
node maker make-auth
Our auth routes will be generated in Routes/authRoute/index.js
file.
"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:
/*
|-----------------------------------------------------------
| 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.
/**
* 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:
node maker run-sql-migration
To view our authentication config, head over to App/Config/auth.js file.
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.
Route Authentication
We can now authenticate our routes like so:
Route.get('/user', 'UserController@index',['auth']);
You can also authenticate your route groups like so:
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.
In your PostMan, access the register endpoint using a post method 127.0.0.1:5000/api/register
and input your username, email and password.
Conclusion
Well done! You have learned how to secure your API routes with ExpressWebjs. Need to use ExpressWebjs to build your API or micro-service? I'd bet on ExpressWebjs as the tool of choice for speed and ease of use.
I will be discussing on ExpressWebjs Data Validation in my next article.
You can follow me on twitter @EmekaIgbokwe
You can follow ExpressWebJs on twitter @expresswebjs
and don't forget to star on github ExpressWebJs
Please, let me know if you have any questions in the comment section. 😊
Posted on March 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.