Skip to content

Instantly share code, notes, and snippets.

@rahilb
Created March 18, 2015 14:41
Show Gist options
  • Save rahilb/73362f663a028f1f986c to your computer and use it in GitHub Desktop.
Save rahilb/73362f663a028f1f986c to your computer and use it in GitHub Desktop.
lua token authenticator for nginx
-- an openresty/nginx authenticator that checks bearer tokens with
-- an ID service for use with `access_by_lua_file` nginx directive
local http = require "resty.http"
local hc = http:new()
function abandon_request(status_code, response_body)
ngx.header["WWW-Authenticate"] = "Bearer"
ngx.status = status_code
ngx.say(response_body)
ngx.exit(status_code)
end
local role_restriction = ngx.var.role_restriction
local auth_header = ngx.req.get_headers()["Authorization"]
if (auth_header == nil) then
abandon_request(401, "")
end
local ok, code, headers, status, body = hc:request {
url = "http://127.0.0.1:8080/session",
method = "GET",
headers = { Authorization = {auth_header}}
}
if (code == 200) then
if (role_restriction ~= nil) then
-- TODO: Parse the JSON instead of string.find(_)
if (string.find(body, role_restriction)) then
return
else
abandon_request(403, "")
end
else
return
end
end
abandon_request(code, "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment