Authentication in express with JWT token | e Avni Tech

eavnitech
3 min readApr 5, 2021

Today we will discuss how to authenticate the users in express js with JWT token.

So first let’s understand the JWT token

What is JWT token

JWT stands for javascript web token, which is used to send or receive the data between 2 parties securely.

  • It can be signed with a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
  • JWTs are an open, industry-standard RFC 7519 method.
  • JWT is used for authentication, authorization & for information exchange.

Implementation of JWT in expressjs

Let’s set up the authentication with expressjs, so first, we will install all required npm packages

  • Run npm init to create the package.json, i hope you already know about the npm commands
  • run npm install express to install express.js
  • run npm i jsonwebtoken to install the JWT token package, we will use jsonwebtoken package

Express server setup

Now we will set up the express js server so we will authenticate the end-user.

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})

We have done the express.js server setup now time to implement the jsonwebtoken package.

Now please use the below code in your js file

var jwt = require('jsonwebtoken'); // import the jsonwebtoken at top of your file

Now time to generate the JWT token, there are various way to generate the token like

  • Generate after authenticating the user from DB
  • Generate after signup the user in this tutorial, we are just creating a JWT token API
app.get('/createJwtToken', (req, res) => {
let yourKey = 'yourKey';
var token = jwt.sign({ name: 'eavnitech' }, yourKey);
res.send({token});
});

in case of login, you can call var token = jwt.sign({ name: 'eavnitech' }, yourKey); this code just after authenticating from the DB

so when you hit the API http://localhost:3000/createJwtToken and you will see the JWT token in the API response.

Now time to verify the generated JWT token. there are various way to send the JWT token to the server like

  • send the token in the header (Best way)
  • send in the query param(Not a good way)
  • Send with body data

For now, i have created an API to verify the JWT token

app.get('/verifyJwt', (req, res) => {
let token = req.query.token;
var decoded = jwt.verify(token, yourKey);

res.send({decoded});
});

Please hit http://localhost:3000/verifyJwt?token=<Your JWT token> you need to send the token in the query param.

Authenticate with middleware

Let’s create a middleware so we can authenticate if the JWT token is verified then only we will allow accessing the URL(resource).

As we know there are various ways to send the JWT token from client(browser, mobile App) to the server.

For now, we will send the token in the header as x-auth.

Below is the middleware code, here we are checking the client header and getting the token from it.

after that, we are verifying the token if the JWT token is valid then only the user can access the code in the API else the middleware will send 401 HTTP code status.

var middleware = function(req, res, next){
var token = req.header('x-auth');

jwt.verify(token, yourKey, function(err, decoded) {
if (err) {
res.status(401).send({message:'Please login'});
}
next();
});
}

In the below code, we added the middleware, if the JWT token is valid then only the end-user can access the code.

app.post('/verifyThroughHeader', middleware , (req, res) => {

res.send({result:"Your are authenticated"});
});

Let’s sum up, your index.js file will look like this

const express = require('express')
const app = express()
const port = 3000
var jwt = require('jsonwebtoken');
var yourKey = "yourkey";
app.get('/', (req, res) => {
res.send('Hello World!')
})
var middleware = function(req, res, next){
var token = req.header('x-auth');

jwt.verify(token, yourKey, function(err, decoded) {
if (err) {
res.status(401).send({message:'Please login'});
}
next();
});
}
app.get('/createJwtToken', (req, res) => {
var token = jwt.sign({ name: 'eavnitech' }, yourKey);

res.send({token});
});
app.get('/verifyJwt', (req, res) => {
let token = req.query.token;
var decoded = jwt.verify(token, yourKey);

res.send({decoded});
});
app.post('/verifyThroughHeader', middleware , (req, res) => {

res.send({result:"Your are authenticated"});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})

Conclusion

So we learned how to authenticate the end-user in expressjs with JWT token with middleware and without middleware.

Please give it a try and I will be happy to answer your queries on my Twitter handle Twitter

Originally published at https://eavnitech.com.

--

--