Sample code for 30+ languages & platforms
Lianja

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 Lianja Downloads

Lianja
llSuccess = .F.

loJws = createobject("CkJws")

//  Protected header specifying HMAC-SHA256.
loHeader = createobject("CkJsonObject")
loHeader.UpdateString("alg","HS256")
llSuccess = loJws.SetProtectedHeader(0,loHeader)
if (llSuccess = .F.) then
    ? loJws.LastErrorText
    release loJws
    release loHeader
    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.
loUnprotected = createobject("CkJsonObject")
loUnprotected.UpdateString("kid","signer-key-1")
llSuccess = loJws.SetUnprotectedHeader(0,loUnprotected)
if (llSuccess = .F.) then
    ? loJws.LastErrorText
    release loJws
    release loHeader
    release loUnprotected
    return
endif

llBIncludeBom = .F.
llSuccess = loJws.SetPayload("This is the content to sign.","utf-8",llBIncludeBom)
if (llSuccess = .F.) then
    ? loJws.LastErrorText
    release loJws
    release loHeader
    release loUnprotected
    return
endif

lcBase64Key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
llSuccess = loJws.SetMacKey(0,lcBase64Key,"base64")
if (llSuccess = .F.) then
    ? loJws.LastErrorText
    release loJws
    release loHeader
    release loUnprotected
    return
endif

//  Because an unprotected header is present, the JWS is produced in a JSON serialization form.
lcJwsJson = loJws.CreateJws()
if (loJws.LastMethodSuccess = .F.) then
    ? loJws.LastErrorText
    release loJws
    release loHeader
    release loUnprotected
    return
endif

? lcJwsJson


release loJws
release loHeader
release loUnprotected