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
  • Restricting access: Swagger Security and x-flat-jwt
  • Sending JWT claims upstream: out-header
  • Accessing JWT claims: out-var
  • All files together
  • See also

Was this helpful?

  1. Cookbook

Protecting Access using JWT Tokens

PreviousProcessing Upstream ResponsesNextReference

Last updated 4 years ago

Was this helpful?

Imagine you had a to an API, e.g. httpbin.org.

swagger.yml:

swagger: "2.0"
basePath: /
paths:
  /httpbin/**:
    x-flat-proxy:
      origin: https://httpbin.org
      stripEndpoint: true

Sending a request to FLAT running on localhost port 8080 results in:

$ curl -i http://localhost:8080/httpbin/anything
HTTP/1.1 200 OK
…
Content-Type: application/json

{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "deflate, gzip",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.29.0",
    "X-Amzn-Trace-Id": "…"
  },
  "json": null,
  "method": "GET",
  "origin": "…",
  "url": "https://httpbin.org/anything"
}

That's what you would expect from httpbin.org, right?

Restricting access: Swagger Security and x-flat-jwt

Swagger has a two-part feature to describe protected access to routes: securityDefinitions (what sort of protection is applied …) and security (… to which routes), e.g.:

swagger: "2.0"
basePath: /
securityDefinitions:
  JWTCookie:
    type: apiKey
    in: header
    name: Cookie
paths:
  /httpbin/**:
    security:
      - JWTCookie: []

This documentation feature, with some extensions, is used to make FLAT actually permit access to the route only if a valid JWT token is presented.

First, we define the name of the cookie expected to accompany the API request:

…
securityDefinitions:
  JWTCookie:
    type: apiKey
    in: header
    name: Cookie
    x-flat-cookiename: authtoken    # ⬅ specify the cookie name
…
…
  JWTCookie:
    type: apiKey
    in: header
    name: Cookie
    x-flat-cookiename: authtoken
    x-flat-jwt:                     # ⬅ our JWT configuration:
      key:                          # ⬅ the key to decode the JWT …
        file: pubkey.pem            # ⬅ … is read from the file pubkey.pem
      alg: RS256                    # ⬅ the signing algorithm is RS256
…

The specified key is a public key, read from the file pubkey.pem, e.g.:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGSd+sSTss2uOuVJKpumpFAaml
t1CWLMTAZNAabF71Ur0P6u833RhAIjXDSA/QeVitzvqvCZpNtbOJVegaREqLMJqv
FOUkFdLNRP3f9XjYFFvubo09tcjX6oGEREKDqLG2MfZ2Z8LVzuJc6SwZMgVFk/63
rdAOci3W9u3zOSGj4QIDAQAB
-----END PUBLIC KEY-----

That's all. Now FLAT will only permit requests if they supply a token that bear an RS256 signature that was created with the private key that matches the given public key.

Usually, you would get the key and algorithm from your identity provider (e.g. an OAuth2 authorization server). That service would be responsible for issuing JWT tokens for your users.

For this tutorial we have prepared a couple of JWT tokens for you to try out different situations:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIiwiZXhwIjoxNTkwNDkxNTI4fQ.lJnUpBzMx84_5yigeHeLw4f8sbdSdu_7fWr1--t7EAp8v8K-kSmVYUGnR0Jx4o_ZE84N2M72Kn1pKssrzgTHsFi7txcZHHz_JqgnPgKqsZwjrmWDC-XVvdrSXjAsPO6wn0qy3KEMT1y6Z8YQA4ZyzA1dDsRRIUFiNrgF6_b5pC4
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIn0.bNXv28XmnFBjirPbCzBqyfpqHKo6PpoFORHsQ-80IJLi3IhBh1y0pFR0wm-2hiz_F7PkGQLTsnFiSXxCt1DZvMstbQeklZIh7O3tQGJyCAi-HRVASHKKYqZ_-eqQQhNr8Ex00qqJWD9BsWVJr7Q526Gua7ghcttmVgTYrfSNDzU

Let's give it a try:

$ curl -i http://localhost:8080/httpbin/anything
HTTP/1.1 403 Forbidden
…
Content-Type: application/json

{
  "error": {
    "message": "Security violation",
    "status": 403,
    "requestID": "Xsz@QAv8CEBZfWbmQhKLIQAAAII",
    "info": [
      "JWT Security (JWTCookie): No Cookie header sent"
    ],
    "code": 3206
  }
}

Ah, yes, we forgot to present a token in the authtoken cookie. But we see, that the protection works.

Let's try again with the first token:

$ curl -i -H "Cookie: authtoken=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIiwiZXhwIjoxNTkwNDkxNTI4fQ.lJnUpBzMx84_5yigeHeLw4f8sbdSdu_7fWr1--t7EAp8v8K-kSmVYUGnR0Jx4o_ZE84N2M72Kn1pKssrzgTHsFi7txcZHHz_JqgnPgKqsZwjrmWDC-XVvdrSXjAsPO6wn0qy3KEMT1y6Z8YQA4ZyzA1dDsRRIUFiNrgF6_b5pC4" http://localhost:8080/httpbin/anything
HTTP/1.1 403 Forbidden
…
Content-Type: application/json

{
  "error": {
    "message": "Security violation",
    "status": 403,
    "requestID": "Xsz80Av8CEBZfWbmQhKLIAAAAIE",
    "info": [
      "JWT Security (JWTCookie): Invalid JWT: Token has expired."
    ],
    "code": 3206
  }
}

Hmm, expired. So this one is too old. (Access tokens typically have a restricted period of use.)

OK, let's use the other token:

$ curl -i -H "Cookie: authtoken=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIn0.bNXv28XmnFBjirPbCzBqyfpqHKo6PpoFORHsQ-80IJLi3IhBh1y0pFR0wm-2hiz_F7PkGQLTsnFiSXxCt1DZvMstbQeklZIh7O3tQGJyCAi-HRVASHKKYqZ_-eqQQhNr8Ex00qqJWD9BsWVJr7Q526Gua7ghcttmVgTYrfSNDzU" http://localhost:8080/httpbin/anything
HTTP/1.1 200 OK
…
Content-Type: application/json

{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "deflate, gzip",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.29.0",
    "X-Amzn-Trace-Id": "…"
  },
  "json": null,
  "method": "GET",
  "origin": "…",
  "url": "https://httpbin.org/anything"
}

Tada!

By the way, apart from cookies, this also works similarly with the Authorization: Bearer … header:

…
securityDefinitions:
  JWTBearer:
    type: apiKey
    in: header
    name: Authorization             # ⬅
    x-flat-jwt:
      key:
        file: pubkey.pem
      alg: RS256
paths:
  /httpbin/**:
    security:
      - JWTBearer: []

You can try that with

$ curl -i -H "Authorization: Bearer eybGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIn0.bNXv28XmnFBjirPbCzBqyfpqHKo6PpoFORHsQ-80IJLi3IhBh1y0pFR0wm-2hiz_F7PkGQLTsnFiSXxCt1DZvMstbQeklZIh7O3tQGJyCAi-HRVASHKKYqZ_-eqQQhNr8Ex00qqJWD9BsWVJr7Q526Gua7ghcttmVgTYrfSNDzU" http://localhost:8080/httpbin/anything

But there are two additional features that can be quite handy: out-header and out-var.

Sending JWT claims upstream: out-header

…
    x-flat-jwt:
      key:
        file: pubkey.pem
      alg: RS256
      out-header: JWT               # ⬅ the name of the request header with the JWT claims
…
$ curl -i -H "Cookie: authtoken=eybGciOiJSUzI1NiJ9.eyJzdWIiOiJzb21lX3VzZXIiLCJpc3MiOiJzb21lX3Byb3ZpZGVyIn0.bNXv28XmnFBjirPbCzBqyfpqHKo6PpoFORHsQ-80IJLi3IhBh1y0pFR0wm-2hiz_F7PkGQLTsnFiSXxCt1DZvMstbQeklZIh7O3tQGJyCAi-HRVASHKKYqZ_-eqQQhNr8Ex00qqJWD9BsWVJr7Q526Gua7ghcttmVgTYrfSNDzU" http://localhost:8080/httpbin/anything
HTTP/1.1 200 OK
…
Content-Type: application/json

{
…
  "headers": {
…
    "Jwt": "{\"sub\":\"some_user\",\"iss\":\"some_provider\"}",
…
  },
…
}

Accessing JWT claims: out-var

…
    x-flat-jwt:
      key:
        file: pubkey.pem
      alg: RS256
      out-header: JWT
      out-var: $the_claims          # ⬅
…
swagger: "2.0"
…
x-flat-init: init.xml
paths:
…

with init.xml:

<flow>
  <log>
  {
    "JWT-Claims": {{ $the_claims }}
  }
  </log>
</flow>
{…,"type":"flat_access",…,"JWT-Claims":{"sub":"some_user","iss":"some_provider"}}

Here you see the two claims from the JWT token.

All files together

swagger.yaml:

swagger: "2.0"
basePath: /
securityDefinitions:
  JWTCookie:
    type: apiKey
    in: header
    name: Cookie
    x-flat-cookiename: authtoken
    x-flat-jwt:
      key:
        file: pubkey.pem
      alg: RS256
      out-var: $the_claims
      out-header: JWT
x-flat-init: init.xml
paths:
  /httpbin/**:
    security:
      - JWTCookie: []
    x-flat-proxy:
      origin: https://httpbin.org
      stripEndpoint: true

pubkey.pem:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGSd+sSTss2uOuVJKpumpFAaml
t1CWLMTAZNAabF71Ur0P6u833RhAIjXDSA/QeVitzvqvCZpNtbOJVegaREqLMJqv
FOUkFdLNRP3f9XjYFFvubo09tcjX6oGEREKDqLG2MfZ2Z8LVzuJc6SwZMgVFk/63
rdAOci3W9u3zOSGj4QIDAQAB
-----END PUBLIC KEY-----

init.xml:

<flow>
  <log>
  {
    "JWT-Claims": {{ $the_claims }}
  }
  </log>
</flow>

See also

Now, you don't want anyone except authorized users to use this proxy. This is typically achieved with access tokens. Some tokens are JSON Web Tokens (), while others are opaque.

This defines a security scheme object (named JWTCookie), meaning that some sort of cookie is needed to access certain routes. This is applied to the /httpbin/**.

Then we specify the for decoding the JWT token:

With you can send the whole set of claims from the JWT upstream:

With out-var you can specify the name of a where FLAT will store the JSON claims encoded in the JWT, in order to make them available for further processing. E.g.

We can log the claims by adding a to an :

If you look at the and try again with a valid token, you'll notice:

If you want to know, how to perform some additional checks on the JWT, visit the cookbook .

(reference)

(reference)

(cookbook)

JWT
variable
FLAT logs
Performing Additional Checks on JWT Access Tokens
FLAT Security
Routing: Init Flow and FLAT Proxies
Encoding and Decoding JWT
log action
wildcard path
configuration
out-header
proxy
init flow