Using JWT Authentication with OpenResty Lua
Validating a JWT on every request is exactly the kind of work you’d rather not push down into your backend. In this post I’ll show how to handle it right at the edge, authenticating Nginx using JWT with OpenResty Lua.
It helps to first know what OpenResty actually is. OpenResty is a web application server that uses Nginx at its core. Because of that, you get all the familiar Nginx modules, plus the ability to drop in Lua modules to extend things further, which is exactly what makes this approach possible.
The verification itself comes from an authenticator written in Lua, so we clone this repository to get the file: https://github.com/ubergarm/openresty-nginx-jwt
With that file in place, the setup feels a lot like basic authentication. We configure our nginx.conf to add the following.
env JWT_SECRET; #our secret
location / {
access_by_lua_file /bearer.lua;
proxy_pass http://127.0.0.1:8080;#our backend port
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Auth-Request-Redirect $request_uri;
}
From here on, any request carrying a Bearer authorization header will be checked against that secret before it ever reaches the server.