Skip to content

JWT - Json Web Token

Validating the JWT

NodeJS

import jwt from 'jsonwebtoken'

// Provide MARKETPLACE_ELEMENTS_OFFER_PUBLIC_KEY as an environmental variable
// The public key in the offer configuration page is base64 encoded
const publicKey = Buffer.from(process.env.MARKETPLACE_ELEMENTS_OFFER_PUBLIC_KEY, 'base64').toString()

// The request body is a JSON object with a payload property containing the JWT
// you will need to get the request body from your web framework handling the request
const token = requestBody.payload
const decodedToken = jwt.verify(token, publicKey, { algorithms: ['RS256'] })
if (typeof decodedToken === 'string') {
  context.log.warn({ decodedToken }, 'Token validation error')
  //Decoding/verification could be a bad request or an internal server error
  //Assuming the public key is set correctly, it will be bad request
  throw badRequest({ error: 'Invalid token' })
}

// decodedToken is ready to use

dotnet

namespace WebApi.Authorization;

using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebApi.Entities;
using WebApi.Helpers;

public interface IJwtUtils
{
    public JwtSecurityToken? ValidateToken(string token);
}

public class JwtUtils : IJwtUtils
{
    private readonly AppSettings _appSettings;

    public JwtUtils(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
    }

    public int? ValidateToken(string token)
    {
        if (token == null)
            return null;

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_appSettings.ArkahnaElementsOfferPublicKey);
        try
        {
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                // set clockSkew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;

            return jwtToken;
        }
        catch
        {
            // return null if validation fails
            return null;
        }
    }
}

powershell

# Install the System.IdentityModel.Tokens.Jwt NuGet package
Install-Package System.IdentityModel.Tokens.Jwt -Force

# Specify the JWT token and the base64 encoded public key
$jwtToken = "<your JWT token>"
$publicKey = "<your base64 encoded public key>"

# Convert the base64 encoded public key to a byte array
$publicKeyBytes = [System.Convert]::FromBase64String($publicKey)

# Create a new instance of the RSACryptoServiceProvider class using the public key
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$rsa.ImportSubjectPublicKeyInfo($publicKeyBytes, [ref]$null)

# Create a new instance of the JwtSecurityTokenHandler class
$jwtHandler = New-Object System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler

# Create a new instance of the TokenValidationParameters class and set the public key
$tokenValidationParameters = New-Object System.IdentityModel.Tokens.TokenValidationParameters
$tokenValidationParameters.IssuerSigningKey = New-Object System.IdentityModel.Tokens.RsaSecurityKey($rsa)

# Decode and validate the JWT token using the public key
$jwtTokenObj = $jwtHandler.ReadJwtToken($jwtToken)
$claimsPrincipal = $jwtHandler.ValidateToken($jwtTokenObj, $tokenValidationParameters, [ref]$null)

# Access the claims in the JWT token
$jwtClaims = $claimsPrincipal.Claims
foreach ($claim in $jwtClaims) {
    Write-Host "Claim: $($claim.Type) Value: $($claim.Value)"
}