FLAT
CouperSevenval TechnologiesDocker ImageGithub
master
master
  • Changelog
  • FLAT
  • Administration
    • Configuration
    • Docker
    • Logging
  • Cookbook
    • Using the Built-in Mocking
    • Performing Additional Checks on JWT Access Tokens
    • Logging Custom Fields
    • Using Environment Variables
    • Handling Errors with an Error Flow
    • File Serving
    • Forwarding a Request to an Upstream API
    • Extracting Common Initialization Flow Tasks
    • Encoding and Decoding JWT
    • Passing Header Fields to the Client
    • How can I pass an arbitrary header field to an upstream system?
    • Performing Additional Checks on JWT Access Tokens
    • Proxying requests to Upstream APIs
    • Increasing the Request Timeout
    • How can I see what the client requested?
    • Using Swagger UI for API Documentation
    • Testing API Requests
    • Testing with Backend Requests
    • Testing Templates
    • Sending POST Requests
    • Processing Upstream Responses
    • Protecting Access using JWT Tokens
  • Reference
    • Configuration
    • Debugging
    • flat CLI
    • Flow
    • Variables
    • OpenAPI / Swagger Integration
    • OpenAPI
      • CORS - Cross-Origin Resource Sharing
    • OpenAPI
      • Differences from Swagger
    • OpenAPI
      • Mocking
    • OpenAPI
      • Routing
    • OpenAPI
      • Security
    • OpenAPI
      • Upstream APIs
    • OpenAPI
      • Validation
    • Flow Actions
      • assert Action
      • auth Action
      • backend-flow Action
      • copy Action
      • debug Action
      • dump Action
      • echo Action
      • error Action
      • eval Action
      • log Action
      • nameshave Action
      • pass-body Action
      • proxy-request Action
      • regex Action
      • request Action
      • requests Action
      • serve Action
      • set-config Action
      • set-env Action
      • set-response-headers Action
      • set-status Action
      • sub-flow Action
      • template Action
      • test-request Action
      • xslt Action
    • Functions
      • apply-codecs()
      • array-reverse()
      • array()
      • base64-decode()
      • base64-encode()
      • body()
      • calc-signature()
      • capitalize-first()
      • content()
      • decrypt-xml()
      • decrypt()
      • encrypt()
      • ends-with()
      • file-exists()
      • fit-document()
      • fit-log()
      • fit-serialize()
      • get-log()
      • has-class()
      • html-parse()
      • join()
      • json-doc()
      • json-parse()
      • json-stringify()
      • json-to-csv()
      • json-to-xml()
      • jwt-decode()
      • jwt-encode()
      • ldap-lookup()
      • ldap-query()
      • lookup()
      • matches()
      • md5()
      • replace()
      • sort()
      • split()
      • tolower()
      • toupper()
      • trim()
      • unixtime()
      • urldecode(), url-decode()
      • urlencode(), url-encode()
      • uuid3() and uuid4()
      • verify-signature()
      • verify-xmldsig()
      • xml-parse()
      • xml-to-json()
    • Templating
      • {{,}}
      • Comment {{// …}}
      • Dot {{.}}
      • Conditional `{{if <condition>}} … {{elseif <condition> }} … {{else}} … {{end}}
      • loop
      • ?? Operator
      • Object XML Notation (OXN)
      • Pair Producer {{: …}}
      • Placeholder
      • Template Variables
      • with
    • Testing
  • Tutorial
Powered by GitBook
On this page
  • Pitfalls
  • See also

Was this helpful?

  1. Cookbook

Encoding and Decoding JWT

PreviousExtracting Common Initialization Flow TasksNextPassing Header Fields to the Client

Last updated 4 years ago

Was this helpful?

This snippet demonstrates how to use the jwt-encode() and jwt-decode() functions to work with .

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:

$ FLAT_JWT_SECRET=YXNkZg== flat start

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:

$ curl localhost:8080/api/jwt?user=alice\&role=admin\&customer=flintstone
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWxpY2UiLCJyb2xlIjoiYWRtaW4iLCJjdXN0b21lciI6ImZsaW50c3RvbmUiLCJleHAiOjE1NjA3OTAxMjR9.6eGqRQXGZ1sU9nQz2sBIAHoXJUDe_Vf3TsPdv9pB_9M

Later, we can decode and validate the user params with this call:

$ curl localhost:8080/api/jwt?token=eyJ0eXAiOiJKV1QiL…
{
  "user": "alice",
  "role": "admin",
  "customer": "flintstone",
  "exp": 1560789571
}

You have to be quick copy-pasting it, because the time-to-live (encoded as exp param) is set to 20 seconds :)

<flow>
  <!-- decode and dump content -->
  <if test="$request/get/token">
    <template>
      {{ jwt-decode($request/get/token, $env/FLAT_JWT_SECRET) }}
    </template>
    <break/>
  </if>

  <!-- read user params from query string ?user=…&customer=…&role=… -->
  <template in="$request" out="$data">
    {
      {{: $request/get/user | $request/get/customer | $request/get/role }}
    }
  </template>

  <!-- generate token -->
  <eval out="$jwt">jwt-encode($data, $env/FLAT_JWT_SECRET, 20)</eval>
  <dump in="$jwt" />
</flow>

Pitfalls

For HMAC based algorithms, the JWT functions expect the key to be base64 url encoded.

You can do this on-the-fly:

<template out="$jwt">
  {{ jwt-encode($data, base64-encode($env/FLAT_JWT_SECRET), 20) }}
</template>

Of course, you could also do that once outside of FLAT before setting the env var:

$ echo -n "YXNkZg==" | base64
WVhOa1pnPT0=
$ FLAT_AUTH0_JWT_SECRET=WVhOa1pnPT0= flat start

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:

$ openssl genrsa > privateAndPublic.key
$ tail -n +2 privateAndPublic.key | head -n -1 | tr -d '\n'
MIIEowIB[...]

To extract the public key for signature verification in the required format:

$ openssl rsa -in privateAndPublic.key -outform PEM -pubout -out public.key
$ tail -n +2 public.key | head -n -1 | tr -d '\n'
MIIBIjANBgkqhki[...]

Note that, with RSASSA based algorithms, you have to specify the algorithm in the jwt-decode() function.

See also

But some "bare keys" may already look base64 encoded. for example, uses base64 strings as keys. They need another base64-encode() to be used with jwt-decode().

(reference)

(reference)

(cookbook)

JSON Web Tokens
Auth0
jwt-encode()
jwt-decode()
Protecting Access using JWT Tokens