Encoding and Decoding JWT
This snippet demonstrates how to use the jwt-encode()
and jwt-decode()
functions to work with JSON Web Tokens.
We want to have the JWT Secret (used for signing and verifying a JWS) configurable via an environment variable.
In a development setup, we can simply define a shell variable that starts with FLAT_
. flat
will forward all FLAT_*
variables to the docker container:
The secret must be base64-url encoded. We use our favorite passphrase asdf
here.
When FLAT is running, we can obtain a token built with user params provided via query params:
Later, we can decode and validate the user params with this call:
You have to be quick copy-pasting it, because the time-to-live (encoded as exp
param) is set to 20 seconds :)
Pitfalls
For HMAC
based algorithms, the JWT functions expect the key to be base64 url encoded.
But some "bare keys" may already look base64 encoded. Auth0 for example, uses base64 strings as keys. They need another base64-encode()
to be used with jwt-decode()
.
You can do this on-the-fly:
Of course, you could also do that once outside of FLAT before setting the env var:
For RSASSA
based algorithms, the JWT functions expect the key to be PEM encoded, but without the BEGIN
and END
lines, and without any line breaks. To generate the private and public keys in this format:
To extract the public key for signature verification in the required format:
Note that, with RSASSA
based algorithms, you have to specify the algorithm in the jwt-decode()
function.
See also
jwt-encode()
(reference)jwt-decode()
(reference)Protecting Access using JWT Tokens (cookbook)
Last updated