This content originally appeared on DEV Community and was authored by Tayfun Akgüç
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.
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.
# 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 to get public/private key pair.
Folder Structure
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
-
signToken()
: Takes payload object as parameter and returns the token as string. -
verifyToken()
Takes token as parameter and returns the payload that we signed.
//* 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
//* 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
node app.js
And you'll see something like this
Thanks a lot for reading.
This content originally appeared on DEV Community and was authored by Tayfun Akgüç
Tayfun Akgüç | Sciencx (2021-08-10T19:30:32+00:00) JWT with RSA Signature. Retrieved from https://www.scien.cx/2021/08/10/jwt-with-rsa-signature/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.