Create JWTs

The following code snippets can be used at the backend to create JWT tokens

/*
Package Details
https://github.com/auth0/node-jsonwebtoken
*/

const jwt = require('jsonwebtoken');

function createAuthToken(authId) {
    const secret = "<gateway_secret>";
    const expiresIn = "1d";
    if (authId) {
        return jwt.sign({
            smallcaseAuthId: authId,
        }, secret, { expiresIn });
    }
    return jwt.sign({
        guest: true,
    }, secret, { expiresIn });
}
// Package Details 
// https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt

using System;
using System.IdentityModel.Tokens.Jwt;
// NuGet Package System.IdentityModel.Tokens.Jwt would be required 
using Microsoft.IdentityModel.Tokens;
// NuGet Package Microsoft.IdentityModel.Tokens would be required
// Nuget Microsoft.IdentityModel.Logging would be required
using System.Text;

public class AuthToken {
  public static string GetToken(string authId = null) {
    const string sec = "<gateway_secret>";
    var expiry = (Int32)(DateTime.UtcNow.AddDays(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    var issuedAt = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sec));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
    var header = new JwtHeader(credentials);
    var payload = new JwtPayload();
    if (authId != null) {
      payload = new JwtPayload {
        {
          "smallcaseAuthId", authId
        }, {
          "exp", expiry
        }, {
          "iat", issuedAt
        },
      };
    } else {
      payload = new JwtPayload {
        {
          "guest", true
        }, {
          "exp", expiry
        }, {
          "iat", issuedAt
        },
      };
    }

    var secToken = new JwtSecurityToken(header, payload);
    var handler = new JwtSecurityTokenHandler();
    var tokenString = handler.WriteToken(secToken);
    return tokenString;
  }
}
# Package Details
# https://pyjwt.readthedocs.io/en/stable/

import jwt
# Would need to install pyjwt package
import datetime

def getAuthToken(authId = None):
  secret = "<gateway_secret>"
  issueAt = datetime.datetime.utcnow()
  expireAt = issueAt + datetime.timedelta(days=1)
  if authId == None:
    return jwt.encode({
      "guest": True,
      "exp": expireAt,
      "iat": issueAt,
    }, secret, algorithm="HS256")
  return jwt.encode({
    "smallcaseAuthId": authId,
    "exp": expireAt,
    "iat": issueAt,
  }, secret, algorithm="HS256")
/*
Package Details
https://github.com/lcobucci/jwt
*/

<?php
    use Lcobucci\JWT\Configuration;
    use Lcobucci\JWT\Signer\Hmac\Sha256;
    use Lcobucci\JWT\Signer\Key\InMemory;

    function getAuthToken($authId = null) {
        $config = Configuration::forSymmetricSigner(
            new Sha256(),
            InMemory::plainText('<gateway_secret>')
        );
        $now = new DateTimeImmutable('@' . time());
        $issuedAt = $now->setTimezone(new DateTimeZone("UTC"));
        $expireAt = $issuedAt->modify("+1 day");
        if (!$authId) {
            return $config->builder()
                ->issuedAt($issuedAt)
                ->expiresAt($expireAt)
                ->withClaim('guest', true)
                ->getToken($config->signer(), $config->signingKey())
                ->toString();
        }
        return $config->builder()
            ->issuedAt($issuedAt)
            ->expiresAt($expireAt)
            ->withClaim('smallcaseAuthId', $authId)
            ->getToken($config->signer(), $config->signingKey())
            ->toString();
    }
?>
/*
Package Details
https://github.com/jwtk/jjwt
*/

/*
Need to add the following dependencies 
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
*/

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Calendar;
import java.security.Key;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.io.*;

class AuthToken {
  private SignatureAlgorithm signatureAlgorithm;
  private Key signingKey;

  AuthToken() {
    String key = "<gateway_secret>";
    this.signatureAlgorithm = SignatureAlgorithm.HS256;
    this.signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), signatureAlgorithm.getJcaName());
  }

  public String getToken() {
    Calendar cal = Calendar.getInstance(); 
    Date issuedAt = new Date();
    cal.setTime(issuedAt); 
    cal.add(Calendar.DATE, 1);
    Date expireAt = cal.getTime();

    String jws = Jwts.builder()
      .claim("guest", true)
      .setExpiration(expireAt) 
      .setIssuedAt(issuedAt)
      .signWith(this.signatureAlgorithm, this.signingKey)
      .compact();
    return jws;
  }
}

/*
Example on how to use above class
*/

class Main {
  public static void main(String[] args) {
    AuthToken tokenHandler = new AuthToken();
    String jwt =  tokenHandler.getToken();
    System.out.println(jwt);
  }
}