JWT with RSA Signature
Published: 2021-08-10 19:30:32

Hello everyone!

In this article we will learn how to sign JSON Web Token with RSA key.

Let’s start!

## Initialize NodeJS Project

First of all, I'm gonna create the project folder. Then install `jsonwebtoken` package.

```bash
cd path/to/your/workspace
# Create project folder
mkdir jwt-rsa
# Change directory
cd jwt-rsa
npm init -y
# Install JWT
npm install --save jsonwebtoken
```


## Generate RSA Token 

Now let's generate public and private key. If you increase the key length, token length will be increase too. This means HTTP request body size will be increase. But also it depends what kind of payload we we'll sign.

```bash
# Create a folder named keys
mkdir keys
# Minimum RSA key length is 1024 bits
# Maximum RSA key length is 16384 bits 
# Don't add passphrase
ssh-keygen -t rsa -b 1024 -m PEM -f keys/rsa.key
# Write public key to keys/rsa.key.pub file
openssl rsa -in keys/rsa.key -pubout -outform PEM -out keys/rsa.key.pub

```

Also you can use this [online tool](https://travistidwell.com/jsencrypt/demo/) to get public/private key pair.

## Folder Structure

![Folder Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmnelexi0r3oecxij8uh.png)

## Implementation of `signToken()` and `verifyToken()` Methods

Note that, I'm not gonna use all jwt options like `issuer`, `audience` or `expiresIn` etc... except `algorithm`

This is how we sign a token synchronously. This usage, returns the JSON Web Token as string.
* `jwt.sign(payload, secretOrPrivateKey, options)`

### jwt.js 

1. `signToken()`: Takes payload object as parameter and returns the token as string.
2. `verifyToken()` Takes token as parameter and returns the payload that we signed.

```js
//* jwt.js
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')

const privateKey = fs.readFileSync(path.join(__dirname, 'keys', 'rsa.key'), 'utf8')
const publicKey = fs.readFileSync(path.join(__dirname, 'keys', 'rsa.key.pub'), 'utf8')


module.exports = {

    signToken: (payload) => {
        try {
            return jwt.sign(payload, privateKey, { algorithm: 'RS256'});
        } catch (err) {
            /*
                TODO throw http 500 here 
                ! Dont send JWT error messages to the client
                ! Let exception handler handles this error
            */
            throw err
        }
    },

    verifyToken: (token) => {
        try {
            return jwt.verify(token, publicKey, { algorithm: 'RS256'});
        } catch (err) {
            /*
                TODO throw http 500 here 
                ! Dont send JWT error messages to the client
                ! Let exception handler handles this error
            */
            throw err
        }
    }

}

```

## Signing Payload and Verifying Token

```js
//* app.js
const { signToken, verifyToken } = require('./jwt')

const token = signToken({ userId: 1 })
console.log({ token })

const verified = verifyToken(token)
console.log({ verified }) 
```

## Let's See What Happened

Run app.js

```bash
node app.js
```

And you'll see something like this

![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6nph4r2zptm5291du6f.png)

[Github repository](https://github.com/tayfunakgc/jwt-rsa)

Thanks a lot for reading.