Question
· Jul 30

Generate JWT token

Hi there,

My purpose is to encrypt a communication using JWT tokens.  I am developing on IRIS and my purpose is to generate a JWT token that will run on an older version of Cache (so I have to use functions that are compatible with the older version, Cache).

I wrote this code in IRIS:

s username = "user-test123"
set st = ##class(%OAuth2.Utils).TimeInSeconds($ztimestamp,0)
set et = ##class(%OAuth2.Utils).TimeInSeconds($ztimestamp, 60*15)

s payload = {"id": "test-id-123", "username": "test-username"}
s payload.exp = et
s payload.time = st

s alg = "HS256"
s JOSE("sigalg") = alg

s secret = "Dw/G:+@%VR[a$LV,D4L{5+(4I}+zf+ER" // $system.Encryption.GenCryptRand(32)
s secret = $System.Encryption.Base64Encode(secret)

s jwks = { "keys": [{ "alg": (alg), "k": (secret) }] }
s jwks = jwks.%ToJSON()

d ##class(%OAuth2.JWKS).AddOct("HS256",secret,.jwks)

s jwks =  ##class(%DynamicAbstractObject).%FromJSON(jwks)

This code works and the output is so:

 USER>zw
 
JOSE("sigalg")="HS256"
alg="HS256"
et=1722327153
jwks=<OBJECT REFERENCE>[38@%Library.DynamicObject]
payload=<OBJECT REFERENCE>[1@%Library.DynamicObject]
secret="RHcvRzorQCVWUlthJExWLEQ0THs1Kyg0SX0remYrRVI="
st=1722326253
username="user-test123"

USER>zw jwks
jwks={"keys":[{"alg":"HS256","k":"RHcvRzorQCVWUlthJExWLEQ0THs1Kyg0SX0remYrRVI="},{"kty":"oct","k":"UkhjdlJ6b3JRQ1ZXVWx0aEpFeFdMRVEwVEhzMUt5ZzBTWDByZW1ZclJWST0","alg":"HS256"}]}  ; <DYNAMIC OBJECT>

%OAuth2.JWKS.AddOct  generated a key in the 3rd argument, "jwks".   In the same argument I passed the input key, that is jwks.keys.k = "...secret...".

I discovered this by chance, trying many possibilities.   There is no place where I could find a working example that generated a pool of keys of type OAuth2.JWKS.

My first question is, why does it work in this form and, is there a simpler way to generate the JWKS ?

Next, the purpose is to encode a json.  In order for OAuth2.JWT.ObjectToJWT to work, I had to remove the key {"alg":"HS256","k":"RHcvRzorQCVWUlthJExWLEQ0THs1Kyg0SX0remYrRVI="}  that I initially inserted in jwks and keep only the key generated by OAuth2.JWKS.AddOct.  So I did so:

s newjwks = {}
s newjwks.keys=[]
d newjwks.keys.%Push(jwks.%Get("keys").%Get(1))
s newjwks = newjwks.%ToJSON()

d ##class(%OAuth2.JWT).ObjectToJWT(.JOSE, payload, newjwks, newjwks, .JWT)

This indeed worked , the output is so:

USER>w newjwks
{"keys":[{"kty":"oct","k":"UkhjdlJ6b3JRQ1ZXVWx0aEpFeFdMRVEwVEhzMUt5ZzBTWDByZW1ZclJWST0","alg":"HS256"}]} 

USER>w JWT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InRlc3QtaWQtMTIzIiwidXNlcm5hbWUiOiJ0ZXN0LXVzZXJuYW1lIiwiZXhwIjoxNzIyMzI3MTUzLCJ0aW1lIjoxNzIyMzI2MjUzfQ.dEqq_RHJ_1GEjTLFaklNSfAAAZP9B_PgXbUD1aH2Vkk
USER>

Here, I do not understand why I had to remove the initial key and keep only {"kty":"oct","k":"UkhjdlJ6b3JRQ1ZXVWx0aEpFeFdMRVEwVEhzMUt5ZzBTWDByZW1ZclJWST0","alg":"HS256"} in newjwks.

Product version: Caché 2018.1
Discussion (0)1
Log in or sign up to continue