Authentication in express with JWT token | e Avni Tech
Tags: node, express, jwt
Published: 2021-04-05 02:02:19

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. <br/>
- 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](https://eavnitech.com/blog/what-is-npm-and-how-it-works)

- run `npm install express` to install express.js 
- run `npm i jsonwebtoken` to install the JWT token package, we will use [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken) package


### Express server setup 
Now we will set up the express js server so we will authenticate the end-user.
- Please create an `index.js` file and add the below code.
```javascript

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

```javascript


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

```javascript
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 authenticate 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
```javascript

app.post('/verifyJwtPostBody', (req, res) => {
	let token = req.body.token;
	var decoded = jwt.verify(token, yourKey);
	
	res.send({decoded});
});

```

You can access the API by the post request on `http://localhost:3000/verifyJwt` and send the `token` in the body param.
Your body will be look like this
```javascript

POST /verifyJwtPostBody HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Content-Length: 24

{"token" : "your token"}

```

### 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.


```javascript

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.
```javascript

app.post('/verifyThroughHeader', middleware , (req, res) => {
	
	res.send({result:"Your are authenticated"});
});


```

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

```javascript


const express = require('express')
const app = express()
const port = 3000

var jwt = require('jsonwebtoken');
var yourKey = "yourkey";
var bodyParser = require('body-parser')
app.use(bodyParser.json())



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.post('/verifyJwtPostBody', (req, res) => {
	let token = req.body.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}`)
})

```
Your `package.json` will look like this 
```javascript

{
  "name": "authentication-in-express-with-jwt-token",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1"
  }
}

```
### 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](https://twitter.com/eavnitech)