NodeJS

Prerequisites

To be able to decode JWT token with JS you need to install jsonwebtoken package.

The best way to install it is through an npm package installer:

$ npm install jsonwebtoken

jsonwebtoken usage

First, you need to import the jsonwebtoken package:

const jwt = require('jsonwebtoken');

Second, we need to read and store a public key (used to decrypt a token). You need to get it from a dashboard beforehand and store somewhere near your project (./keys/id_rsa.pub).

const PUBLIC_KEY = fs.readFileSync('/path/to/public/key_public.pem'); // get public key

Then, we need to implement a function to verify a token using a public key:

function verifyJwt(token) {
    try {
        return jwt.verify(token, PUBLIC_KEY, { algorithms: ['RS256'] });
    }
    catch(e) {
        return;
    }
}
const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJjaGFsbGVuZ2VfaWQiOiI4OTMzZTU3Mi1iZjI1LTRlZmUtYmNiNC03NzQ5NTc3MjFlYzAiLCJyZXN1bHQiOjAuOTQ5NDQ3NTU2MDI4NzU2LCJpYXQiOjE1NzgzMzc5NzQsImV4cCI6MTU3ODMzODAzNH0.WNR1Om3Gok4xs6HmIwYBrYtMtH3AVqboSK8KXxvTh2bkyWeBNOzzy-oR8mlZk3TIWtn0c5JRMevFsZuvdNd8lAWrGCiZ3hrIixwrXii4vvHLr3irhZnuWSLUpkLr66dN_sZSxBsdt-IlVU_um9RjUpCjdISu9kqyRDcoTvOfrg8krQBDTT7tfuZy-rwq_4dqCKrGZXWQfT7ym_KOmhOwW_cPCuBPC1GPlQs-cfCjEc9QJJEkHzVKZflzyC158gF6BA6kxgoi-gqIFOcbNdeaBvfqfdyDGv1Zl9N3sxW8kjurtFxnw8Yyz14vyGrLWutunpAOBDpjc6y9wdeKXDTV8w';

verifyJwt(token);

Result

If token is correct and did not expire, you'll receive a decoded JWT structure:

{
  "challenge_id": "3aa67786-d8cb-4ed5-ae83-ae7ace27e372",
  "result": 0.949447556028756,
  "iat": 1578001068,
  "exp": 1578001128
}

You can obtain challenge result in a result field.

Last updated