In this post we will use NGINX LUA to create a customized auth request. In our case we will use a POST request to the auth server, and will check the response header to decide if we want to allow the access.
To create an NGINX with LUA support, see my previous post.
Once we have a LUA enabled NGINX, we can configure a protected location:
nginx.conf
server {
listen 8080;
server_name "~.*";
location / {
access_by_lua_block {
if require("myscript").validate("http://my-auth.com") then
return
end
ngx.exit(ngx.HTTP_FORBIDDEN)
}
proxy_pass "http://my-server.com";
}
}
The LUA script in access_by_lua_block, will run our script to validate the request, and in case the result is false, it will block access to the proxy.
The myscript.lua file should reside in /my-lua/myscript.lua (as this is the folder we have specified in the nginx.conf). Since we want to send a request to my-auth.com, we should also include the resty.http library files under /my-lua/resty/. The 3 files can be downloaded from here.
myscript.lua
local myscript = {}
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
local function validate(authUrl)
local httpc = require('.resty.http').new()
local originalHeaders = ngx.req.get_headers()
headers['Content-Type'] = 'application/json'
headers['originalHost'] = ngx.var.host
headers['user'] = headers['user']
local res, err = httpc:request_uri(authUrl, {
method = 'POST',
body = '{}',
headers = headers,
})
if not res then
ngx.log(ngx.STDERR, 'auth request failed: ', err)
return false
end
local status = res.status
local body = res.body
if status ~= 200 then
ngx.log(ngx.ERR, 'auth request returned error: ', err, status, body)
return false
end
local dormant = res.headers['allow']
if allow == 'false' then
return false
end
return true
end
myscript.validate = validate
return myscript
The validate function sends a POST request to the auth server. It adds some headers to the request, sends it, and check the response header to decide whether the auth server had allowed or blocked the access.
No comments:
Post a Comment