The lua-resty-libjwt module is written in Lua with C and is designed to validate JWT tokens directly in Nginx. This prevents requests from being processed by the API, reducing the load on application servers.
Lua bindings to libjwt (https://github.com/benmcollins/libjwt) using FFI
The module was developed using OpenResty and is implemented as a Lua module.
To use Libjwt, you need to provide the path to the jwks.json file, which contains the public keys for JWT token verification.
The module accepts the following parameters:
- An array of paths pointing to files containing JWKS (JSON Web Key Set) keys.
- At least one file must be valid; otherwise, an error will be returned.
Configuration example:
libjwt.validate({
jwks_files = {"/usr/share/tokens/jwks.json"}
})
- Defines the HTTP header field where the JWT token will be retrieved.
- The default value is "Authorization".
- If the token is in a different header, this value can be modified.
Example:
libjwt.validate({
jwks_files = {"/usr/share/tokens/jwks.json"},
header_token = "X-Custom-Token"
})
- Defines whether a 401 Unauthorized response should be automatically returned if the token is invalid.
- The default value is true (automatically generates an error).
- If set to false, the error must be handled manually in
nginx.conf
.
Example:
libjwt.validate({
jwks_files = {"/usr/share/tokens/jwks.json"},
return_unauthorized_default = false
})
If return_unauthorized_default
is false, the error must be handled directly:
local claim, err = libjwt.validate({
jwks_files = {"/usr/share/tokens/jwks.json"},
return_unauthorized_default = false
})
Here is an example of how to configure libjwt in nginx.conf
:
server {
listen 80;
location /private {
content_by_lua_block {
local libjwt = require("resty.libjwt")
local cjson = require("cjson.safe")
local claim, err = libjwt.validate({
jwks_files = {"/usr/share/tokens/jwks.json"}
})
if claim then
local claim_str = cjson.encode(claim) or "Invalid Claim"
ngx.log(ngx.ERR, "JWT Claims: " .. claim_str)
ngx.status = ngx.HTTP_OK
return ngx.say(claim_str)
end
ngx.status = ngx.HTTP_UNAUTHORIZED
local response = { message = "Unauthorized" }
return ngx.say(cjson.encode(response))
}
}
}
The libjwt.validate()
function returns the decoded claim of the token or an error if the token is invalid.
Example:
local claim, err = libjwt.validate()
if claim then
ngx.log(ngx.ERR, "Valid JWT token: ", claim)
else
ngx.log(ngx.ERR, "Token validation error: ", err)
end
- Ensure that the jwks.json file is accessible by Nginx.
- If using a custom header_token, make sure the client is sending it correctly.
- The module improves system efficiency by preventing unauthorized requests from reaching the API.