JSON Web Token: Authorization RESTful API by using JWT
Tags: security, tutorial, webdev, node
Published: 2020-08-26 11:42:36

### ✔ What is JWT

> 💡 JSON Web Token is an open and standard [(RFC 7519)](https://tools.ietf.org/html/rfc7519) way for you to represent your user’s identity securely during a two-party interaction. Particularly, when two systems exchange data you can use JSON Web Token to identify your user without having to send private credentials on every request.


A JWT typically looks like this

```javascript
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo
```

It looks complicated at first sight, but if you understand, the structure of a JWT is just simple as follows
```javascript
<base64-encoded header>.<base64-encoded payload>.<base64-encoded signature>
```
In other words, a well-formed JWT consists of three concatenated Base64url-encoded strings, separated by dots `(.)`, which are:
- Header
- Payload
- Signature

---

### ✔ Build RESTful API with JWT(JSON Web Token)

First let's create a folder with name "_JWT_" and take a look at our project structure
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ut4f6vlnd3f0nel8zvub.PNG)
Then open your command line under JWT directory and write this command

```bash
npm install --save  express body-parser morgan jsonwebtoken 
```

####1 - index.js

```javascript
const express = require('express'),
    bodyParser = require('body-parser'), 
    jwt = require('jsonwebtoken'),
    config = require('./configurations/config'),
    cors = require('cors'),
    app = express();

//set secret
app.set('Secret', config.secret);

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse application/json
app.use(bodyParser.json());

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
app.get('/', function (req, res) {
    res.send('App is running on http://localhost:3000/');
});
```

####2 - configurations/config.js
```javascript
module.exports = {
    secret: "heymynameisminh"
}
```
Now check if everthing is okay 😃 Run this command line. 

```bash
node index.js
```

> ❗️ Make sure that you are standing in the right directory to run index.js file (following our project structure)

Open your browser at http://localhost:3000/ 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lba52x2qulj8nedkvssd.PNG)

Well done! Everything works well. Keep going

####3 - Setting up the authentication system 

Assume the username and password in the database are "_techx_" and "_123_" then write this code in _index.js_ file 

```javascript
app.post('/authenticate', function (req, res) {
    console.log(req.body);
    if (req.body.username !== "techx") res.json({ message: "user not found!" });
    if (req.body.password !== "123") res.json({ message: "please check your password!" });
    const payload = {
        check: true
    }
    let token = jwt.sign(payload, app.get('Secret'), {
        expiresIn: 14000
    });
    res.json({
        message: 'authentication done',
        token: token
    });
});
```

Now let's make a test with Postman

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1a0293fke5j6hidgq309.PNG)

Perfect! 😃 We just sent an HTTP request to the server, which responed with the JWT we asked for. For now, Client's already had the token. Let's move to the next step - _Setting route_

```javascript
const ProtectedRoutes = express.Router();
app.use('/api', ProtectedRoutes);

ProtectedRoutes.use((req, res, next) => {
    let token = req.headers['access-token'];
    console.log(token);
    if (!token) res.send({ message: 'No token provided.' });
    jwt.verify(token, app.get('Secret'), (err, decoded) => {
        if (!err) { req.decoded = decoded; next(); }
        return res.json({ message: 'invalid token' });
    })
});

ProtectedRoutes.get('/getAllProducts', (req, res) => {
    let products = [
        {
            id: 1,
            name: "cheese"
        },
        {
            id: 2,
            name: "carottes"
        }
    ]
    res.json(products)
});
```

Everything have done, now we are comparing two different ways of getting data
- __with Token__

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s5xhsdoflt6jjqp7q2f1.PNG)

- __without Token__ 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/db8yz3k3xh10qxdb7mnu.PNG)
---