Skip to main content
Oath Inc.

2 Generating the JWT Using Different Languages

JWT can be generated using a number of different languages; samples are given below for the following:

JWT generation: Java


Add the following dependency to pom.xml:


<dependency>
    <groupId>org.bitbucket.b_c</groupId>
    <artifactId>jose4j</artifactId>
    <version>0.5.2</version>
</dependency> 
  • clientId = OAuth2 Client ID
  • secret = OAuth2 Client Secret
  • audience = {protocol}://{b2b.host}/identity/oauth2/access_token?realm=<your-realm>
public static String generateJsonWebToken(final String clientId, final String secret, 
final String audience) throws OCAuthException {
 
    JwtClaims claims = new JwtClaims();
    claims.setIssuedAt(NumericDate.now());
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setSubject(clientId);
    claims.setIssuer(clientId);
    claims.setAudience(audience);
    claims.setGeneratedJwtId();
 
    try {
        Key key = new HmacKey(secret.getBytes("UTF-8"));
 
        JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(claims.toJson());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(key);
        jws.setDoKeyValidation(false);
 
        return jws.getCompactSerialization();
 
    } catch (Exception e) {
        throw new OCAuthException("JWT Generation failed", e);
    }
 
}

JWT generation:  JavaScript

Include below CryptoJS dependencies

<script src="//cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64-min.js"></script>

// Defining our token parts
var header = {
 "alg": "HS256",
 "typ": "JWT"
};
var data = {
"aud": "{protocol}://{b2b.host}/identity/oauth2/access_token?realm=<your-realm>",
"iss": "{client_id}",
"sub": "{client_id}",
"exp": “{expiry time in seconds}”,
"iat": “{issued time in seconds}”,
"jti": “{UUID}”
};
var secret = "{client_secret}";
 
function base64url(source) {
 // Encode in classical base64
 encodedSource = CryptoJS.enc.Base64.stringify(source);
 
 // Remove padding equal characters
 encodedSource = encodedSource.replace(/=+$/, '');
 
 // Replace characters according to base64url specifications
 encodedSource = encodedSource.replace(/\+/g, '-');
 encodedSource = encodedSource.replace(/\//g, '_');
 
 return encodedSource;
}
 
var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
var encodedHeader = base64url(stringifiedHeader);
document.getElementById("header").innerText = encodedHeader;
var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
var encodedData = base64url(stringifiedData);
document.getElementById("payload").innerText = encodedData;
var signature = encodedHeader + "." + encodedData;
signature = CryptoJS.HmacSHA256(signature, secret);
signature = base64url(signature);

Back to top

JWT generation: PHP

//install php-jwt
composer require firebase/php-jwt

$audValue = 'https://id.corp.aol.com/identity/oauth2/access_token?realm=<realm>';
$clientId = "<client_id>";
$secret = "<client_secret>"; 

function buildJWT($clientId, $secret, $audValue, $algo = "HS256")
   {
       $now = time();
       $exp = time() + (24 * 60 * 60);
       $jwt_body = array(
           "iss" => $clientId,
           "sub" => $clientId,
           "aud" => $audValue,
           "iat" => $now,
           "exp" => $exp
       );
       return JWT::encode($jwt_body, $secret, "HS256");
   }

Back to top

JWT generation: Node/IO

var jws = require('jws'),
 audValue = 'https://id.corp.aol.com/identity/oauth2/access_token?realm=<realm>',
 clientId = '<client_id>',
 secret = '<client_secret>',
 ttl = 30 * 60,
 now = Math.round(+new Date() / 1000),
 expires = now + ttl,
 jwtBody = {
     iss: clientId,
     sub: clientId,
     aud: audValue,
     exp: expires,
     iat: now
 },
 jwsOps = {
     header: {
         alg: 'HS256'
     },
     payload: JSON.stringify(jwtBody),
     secret: secret
 },
 jws = jws.sign(jwsOps);

Back to top

JWT generation: Ruby

require 'httparty'
require 'jwt'

module JWTTokenGenerator 

 class << self

  private

   def get_token_endpoint(console_uri)
     return console_uri+"/oauth2/access_token"
   end

   def create_jwt(client_id, client_secret,token_endpoint) 
     iat=Time.now.to_i
     exp=iat+600
     payload =
         {
             :iss => client_id,
             :sub => client_id,
             :aud => token_endpoint+'?realm=<realm>',
             :iat => iat,
             :exp => exp
         }
     token = JWT.encode payload, client_secret, 'HS256'
   end

 end

end

Back to top

JWT generation: Python

import base64
import hashlib
import hmac
import json
import time
import urlparse
import requests

def hmac_sha256(key, msg, encode_output=False):

   message = bytes(msg).encode('utf-8')
   secret = bytes(key).encode('utf-8')

   signature = hmac.new(secret, message, digestmod=hashlib.sha256).digest()

   return base64.b64encode(signature) if encode_output else signature
 
def get_access_token(client_config, oauth_code):
   """
   Authenticates a user using Oauth and returns an access token

   :param client_config: A dict with the environment variables. Is different on QA/PROD
   :param oauth_code: The oauth_code included in the url when the user has logged-in in AOL and is redirected to the app
   :return: the oauth access token for the user
   """

   client_id = client_config['CLIENT_ID']
   client_secret = client_config['CLIENT_SECRET']
   realm = client_config['REALM']
   base_url = client_config['BASE_URL']
   redirect_uri = client_config['REDIRECT_URI']

   access_token_url_path = 'identity/oauth2/access_token'

   jwt_header = json.dumps({
       "typ": "JWT",
       "alg": "HS256",
   })

   issue_time = int(time.time())  # Seconds since epoch
   expiry_time = issue_time + 600
   aud = urlparse.urljoin(base_url, '{path}?realm={realm}'.format(path=access_token_url_path, realm=realm))

   jwt_body = {
       "iss": client_id,
       "sub": client_id,
       "aud": aud,
       "exp": expiry_time,
       "iat": issue_time,
   }

   jwt_body = json.dumps(jwt_body)

   jwt_signing_string = base64.b64encode(jwt_header) + '.' + base64.b64encode(jwt_body)

   signature = hmac_sha256(client_secret, jwt_signing_string)

   jwt_signature = base64.b64encode(signature)

   client_assertion = jwt_signing_string + '.' + jwt_signature

   data = {
       'grant_type': 'authorization_code',
       'code': oauth_code,
       'redirect_uri': redirect_uri,
       'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
       'client_assertion': client_assertion,
       'realm': realm,
   }
   resp = requests.post(urlparse.urljoin(base_url, access_token_url_path), data=data)

   result = resp.json()

   return result['access_token']

Back to top