Skip to content

Instantly share code, notes, and snippets.

@ricardo-dlc
Last active August 27, 2020 15:39
Show Gist options
  • Save ricardo-dlc/51fb6569bfe3a889cc32bcec9298bdee to your computer and use it in GitHub Desktop.
Save ricardo-dlc/51fb6569bfe3a889cc32bcec9298bdee to your computer and use it in GitHub Desktop.
Simple Nodejs approach to work with JWT's using JOSE and public/private keys generated with OpenSSL
const jose = require('jose');
const fs = require('fs');
const path = require("path");
// project
// ├── src
// │ └── app.js
// ├── package.json
// └── privatekey.pub
// └── publickey.cer
const privateKey = jose.JWK.asKey(fs.readFileSync(path.resolve(__dirname, '../privatekey.pem')));
const publicKey = jose.JWK.asKey(fs.readFileSync(path.resolve(__dirname, '../publickey.cer')));
// Sign
let jwt = jose.JWT.sign(
{ 'urn:example:claim': 'foo' },
privateKey,
{
algorithm: 'RS512',
expiresIn: '1 min',
header: {
typ: 'JWT'
},
audience: 'urn:example:client_id',
issuer: 'https://op.example.com'
}
);
try {
// Verify JWT and also verify payload content
let payload = jose.JWT.verify(
jwt,
publicKey,
{
issuer: 'https://op.example.com',
audience: 'urn:example:client_id'
}
);
console.log(payload);
} catch (err) {
console.log(err);
if (err instanceof jose.errors.JOSEError && err.code === 'ERR_JWT_EXPIRED') {
console.log('Expired token');
}
else if (err instanceof jose.errors.JOSEError && err.code === 'ERR_JWT_MALFORMED') {
console.log('Invalid token');
}
else if (err instanceof jose.errors.JOSEError && err.code === 'ERR_JWT_CLAIM_INVALID') {
console.log('Claim invalid');
}
else {
console.log('Unexpected error');
}
};

First you need to generate a pair of keys. Generate the private as follows:

openssl genrsa -out privatekey.pem 4096

Then generate the public one using the private generated previously:

openssl req -new -x509 -key privatekey.pem -out publickey.cer

Then proceed to install node dependencies, execute the following in project root directory:

npm install

Finally run:

npm start
{
"name": "use-of-jose",
"version": "1.0.0",
"description": "Use of JOSE library and private/public keys",
"main": "src/app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" "node src/app"
},
"author": "Ricardo de la Cruz <[email protected]>",
"license": "ISC",
"dependencies": {
"jose": "^1.27.0"
}
}
@ricardo-dlc
Copy link
Author

ricardo-dlc commented May 3, 2020

Keys must be created first to avoid errors in app execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment