How can I generate a sha256-RSA-signed JWT token in a Karate (https://github.com/karatelabs/karate) feature file?
https://github.com/karatelabs/karate/issues/1138#issuecomment-629453412 has a nice recipee for doing such for a HMAC-SHA256 (or "HmacSHA256" in Java lingo) token, i.e. using symmetric/shared secret crypto.
But we need asymmetric crypto and the RS256 algo (see RS256 vs HS256: What's the difference? for background)...
OK, think I figured it out :-).
Big thanks to the generous souls providing all the necessary info here:
So the following is an example Karate feature file using
x-jwtheader)To do this one needs to make use of Karate's JavaScript and Java-interop capabilities.
This is our setup to make it work:
We'll use the private key
rsa-4096-private.pem(keep it secret!) of ourrsa-4096-*files to create the signed token.So the essential files for the JWT parts are
rsa-4096-private.pemfor creating the JWTrsa-4096-public.pemfor verifying the token/signature, that's what the api/service/server would do with your JWT token (i.e. this file's not needed/used in our feature file). You can try verifying a resulting token with e.g. https://jwt.io/.Sidenote: public/private key pairs can be generated with e.g.
openssl.As a bonus this example contains using a client certificate and mTLS (which httpbin probably gracefully ignores). If you don't need this you can simply strip the
configure ssl...line and theclient_cert_keystore_passstuff from the karate config file and the command line.Karate feature file:
Karate config file:
As noted you won't need the
client_cert_keystore_passstuff unless you want mTLS. Also, you probably won't need the timeout configurations. I've tested behind a proxy so this also contains some additional config support forhttp_proxy(commented, left in for educational purposes). Adapt to your tastes.Run it:
Note that I'm by no means a Karate expert nor a JavaScript or Java programmer. So this might well not be your idiomatic Karate/JS/Java code. ;-)