JWT Bearer Token authorization with nginx
, openresty
, and lua-resty-jwt
.
An easy way to setup JWT Bearer Token authorization for any API endpoint, reverse proxy service, or location block without having to touch your server-side code.
This example uses the secret, token, and claims from jwt.io:
Server:
docker run --rm \
-it \
-e JWT_SECRET=secret \
-e JWT_ISS=domain.com \
-v `pwd`/nginx.conf:/nginx.conf \
-v `pwd`/bearer.lua:/bearer.lua \
-p 8080:8080 \
heitorcarneiro/openresty-nginx-jwt:1.21.4.1-6-alpine-fat
Generate JWT for testing:
http://jwtbuilder.jamiekurtz.com/
Example:
{
"iss": "domain.com",
"iat": 1681770906,
"exp": 1681777666,
"aud": "www.example.com",
"sub": "[email protected]",
"name": "heitor",
"email": "[email protected]",
"r": [
"viewer",
"accessapproval.approver"
]
}
Client:
curl -i -X GET http://localhost:8080/request -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkb21haW4uY29tIiwiaWF0IjoxNjgxNzcwOTA2LCJleHAiOjE2ODE3Nzc2NjYsImF1ZCI6Ind3dy5leGFtcGxlLmNvbSIsInN1YiI6ImhlaXRvckBleGFtcGxlLmNvbSIsIm5hbWUiOiJoZWl0b3IiLCJlbWFpbCI6ImhlaXRvckBleGFtcGxlLmNvbSIsInIiOlsidmlld2VyIiwiYWNjZXNzYXBwcm92YWwuYXBwcm92ZXIiXX0.r73ZjmC1fBsVDfRve1A9-84E4LhqhOIiL5fszzpD10c'
curl -i -X GET http://localhost:8080/request?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkb21haW4uY29tIiwiaWF0IjoxNjgxNzcwOTA2LCJleHAiOjE2ODE3Nzc2NjYsImF1ZCI6Ind3dy5leGFtcGxlLmNvbSIsInN1YiI6ImhlaXRvckBleGFtcGxlLmNvbSIsIm5hbWUiOiJoZWl0b3IiLCJlbWFpbCI6ImhlaXRvckBleGFtcGxlLmNvbSIsInIiOlsidmlld2VyIiwiYWNjZXNzYXBwcm92YWwuYXBwcm92ZXIiXX0.r73ZjmC1fBsVDfRve1A9-84E4LhqhOIiL5fszzpD10c
Edit nginx.conf
to setup your custom location blocks.
Edit bearer.lua
or create new lua
scripts to meet your specific needs for each location block.
Restart a container and volume mount in all of the required configuration.
To update or build a custom image edit the Dockerfile
and:
docker build -t heitorcarneiro/openresty-nginx-jwt:1.21.4.1-6-alpine-fat .
I originally tried to get auth0/nginx-jwt working, but even the newer forks are not as straight forward as simply using lua-resty-jwt
rock directly.
If you're looking for something beyond just JWT auth, check out kong for all your API middleware plugin needs!
Also Caddy might be faster for a simple project.