By Marone: June 2020
Secure API with Kong
JWT plugin
Goal
In the last article we learn how to protect and consume a API with OAuth2 Plugin. Now we will use JWT Plugin instead.Each incoming request should contain RS256 or HS256 signed JSON Web Tokens (as specified in RFC 7519), kong will use the information related to consumer's JWT credentials such as
issuer, public key and algorithm
to verify the passed access token. If every thing is fine, kong will forward the request to the upstream.
We will use OpenAM access management to obtain a access token in JWT format.
Used technologies
Kong Gateway v2.xDocker 19.x (Running on Windows)
Curl 7.65
Configuring a new service
Step1: Add a service
The Request Body contains:name
: The Service name
url
: The upstream url
Response:
Step2: Add a route
The url specified the service name as attribute{/test-api}
, which we created at step 1. With paths we define a path that match this new route.
Step3: Call the API behind kong
Protect the service
Step1: Enable JWT Plugin
Here we specify the servicetest-api
and of course the plugin name=jwt
Response:
key_claim_name
indicates the name of claim which will be used for validating the access token
header_names
tells us that the JWT will be included in request header Authorization
From now the API is not accessible any more. Calling the API without access token, it will return:
{"message":"Unauthorized"}
Step2: Create a consumer
Step3: Create a JWT credential
What we pass here:- algorithm =
RS256
- Public key in in PEM format
- The key in this case is the name of realm in OpenAM
Let's test
Get Access token
Call the API
We will pass the access token as Authorization headerBehind the scenes (guessed)
- Kong extracts the access token from request header and decode it. The access token looks like:
- It identifies the cosumer and load its JWT credential
- It compares
alg
with the defined onealgorithm
in JWT credential - Kong uses the
public key
from JWT credential to verify the signature - Kong verifies the claims, in our case
iss
- Kong can perform more claims verification, with
config.claims_to_verify
we can tell Kong which other claims should be also verified