Sample code for 30+ languages & platforms
Xbase++

Set the Optional JWS Unprotected Header

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetUnprotectedHeader, which sets the optional unprotected header for a signature.

Background. Unlike the protected header, the unprotected header is not covered by the signature. It is carried in the JSON serialization forms of a JWS, so producing a JWS with an unprotected header yields a JSON serialization rather than compact form.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oJws
LOCAL oHeader
LOCAL oUnprotected
LOCAL nBIncludeBom
LOCAL cBase64Key
LOCAL cJwsJson

nSuccess := 0

oJws := CreateObject("Chilkat.Jws")

//  Protected header specifying HMAC-SHA256.
oHeader := CreateObject("Chilkat.JsonObject")
oHeader:UpdateString("alg", "HS256")
nSuccess := oJws:SetProtectedHeader(0, oHeader)
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    RETURN
ENDIF

//  Set the optional unprotected header for signature 0.  Unlike the protected header, it is not
//  covered by the signature.  It is carried in the JSON serialization forms of a JWS.
oUnprotected := CreateObject("Chilkat.JsonObject")
oUnprotected:UpdateString("kid", "signer-key-1")
nSuccess := oJws:SetUnprotectedHeader(0, oUnprotected)
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    oUnprotected:destroy()
    RETURN
ENDIF

nBIncludeBom := 0
nSuccess := oJws:SetPayload("This is the content to sign.", "utf-8", nBIncludeBom)
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    oUnprotected:destroy()
    RETURN
ENDIF

cBase64Key := "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
nSuccess := oJws:SetMacKey(0, cBase64Key, "base64")
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    oUnprotected:destroy()
    RETURN
ENDIF

//  Because an unprotected header is present, the JWS is produced in a JSON serialization form.
cJwsJson := oJws:CreateJws()
IF (oJws:LastMethodSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    oUnprotected:destroy()
    RETURN
ENDIF

? cJwsJson

oJws:destroy()
oHeader:destroy()
oUnprotected:destroy()