In a Cloudflare Worker I want to verify a JWT toke...
# javascript
s
In a Cloudflare Worker I want to verify a JWT token. I saw that the awesome
kotlin-wrappers
project has already wrappers for that, but I lack sample code how to use it. I find it hard to use it without docs & samples. This is the original JavaScript I want to translate:
Copy code
async function verifyJwt(token, publicKeyBase64Der) {

    const parts = token.split('.');

    if (parts.length !== 3)
        throw new Error("JWT malformed");

    const [headerBase64, payloadBase64, signatureBase64] = parts;

    const signature = base64urlToUint8Array(signatureBase64);
    const data = new TextEncoder().encode(headerBase64 + '.' + payloadBase64);
    const headerJson = JSON.parse(utf8Decode(base64urlToUint8Array(headerBase64)));

    if (headerJson.alg !== "ES256")
        throw new Error("Unsupported Algorithm: " + headerJson.alg);

    const keyData = base64ToUint8Array(publicKeyBase64Der);

    const cryptoKey = await crypto.subtle.importKey(
        "spki",
        keyData,
        {
            name: "ECDSA",
            namedCurve: "P-256",
        },
        false,
        ["verify"]
    );

    const verified = await crypto.subtle.verify(
        {name: "ECDSA", hash: "SHA-256"},
        cryptoKey,
        signature,
        data
    );

    if (!verified)
        throw new Error("Invalid signature");

    return JSON.parse(utf8Decode(base64urlToUint8Array(payloadBase64)));
}
1
a
I can't help but notice that this code is related to what you posted on #C09222272 about AI modifying code
s
Haha, yes. That was the AI changing the algorithm in the original JS code. I made the Cloudflare Worker work in JavaScript, but of course I want a proper Kotlin/JS version. 🙂
Regarding AI, it's no help. It doesn't know kotlin-wrappers at all. It makes up
importPemKey()
methods, because it can't say Sorry, I have no idea how to use the kolin-wrappers
And I can't blame AI for not knowing this, because kotlin-wrappers have no documentation at all right now. 😕
That's why I'm asking here for guidance. 🙂
At least I'm learning things fighting with the original JS docs & guessworking my way through... I wondered why the base64 function is called atob... It's "a to b", "ascii to binary"... sick. 😄
Did what the original JS does, but that's not the answer. 🤷‍♂️
Copy code
val binaryString = atob(JWT_PUBLIC_KEY)

    val bytes = Uint8Array(binaryString.length)

    for (index in 0 .. bytes.length)
        bytes.set(index, binaryString.get(index).code.toByte())

    crypto.subtle.importKey(
        format = KeyFormat.spki,
        keyData = bytes,
        algorithm = EcKeyImportParams(
            name = "ECDSA",
            namedCurve = "P-256"
        ),
        extractable = false,
        keyUsages = arrayOf("verify")
    )
Ok, going to use
com.appstractive:jwt-kt-js:1.2.1
now. That works. I leave the sample issue open - it's needed.