So basically we are building a custom plugin in kong-gateway to write logic for our application’s authorization and token authentication. It goes as follows :
- First, we check if the requested API is Open/Closed, if Open we directly give access and return the response.
- If its Closed then it is required to have a valid bearer jwt token in the header.
- We then validate it by sending the token and some data in header as POST request to our custom-made security-token-validate API, if it returns 200 code then the token is valid and requested resource is returned.
Now, this all is supposed to happen internally in one go, We have reached till 2nd point.
BUT for the 3rd one which includes a rest api call to a service and its response is where we’ve stuck and need help.
Code for handler.lua file -
local http = require("socket.http")
local ltn12 = require("ltn12")-- Import the HTTP module
local CustomHandler = {
VERSION = "1.0.0",
PRIORITY = 10, -- Adjust priority as needed
}
-- Define your array of open URIs
local open_uris = {"/nexus/actuator", "/security/actuator", "/security/auth/validate-token"}
function CustomHandler.access(req)
local requested_path = kong.request.get_raw_path() -- Get the raw request path
-- Check if the requested path is in the array of open URIs
if contains(open_uris, requested_path) then
-- If it is, return the request body
return kong.request.get_body()
else
-- If not, call another API and validate the response
local validate_url = "http://localhost:8088/api/v1.0/security/auth/validate-token" -- Replace with your API URL
local headers = {
--["Authorization"] = kong.request.get_header("Authorization"),
["Authorization"] = "Bearer <token>",
["SERVICE-NAME"] = "PLATFORM",
["AuthResource"] = "HOSPITAL" -- Replace with whatever value you need
}
kong.log("Starting api call ")
local response_body = {}
local _, status_code, _ = http.request{
url = validate_url,
method = "POST", -- Adjust the method as needed
headers = headers, -- Include the headers in the request
sink = ltn12.sink.table(response_body)
}
-- Log the response body (properly concatenated)
--local response_str = table.concat(response_body)
kong.log("Ending api call " , status_code)
if status_code == 200 then
-- Validation successful, do something with the response
kong.log("API call successful. Response: ")
else
-- Validation failed, handle error
kong.response.error(500, "API call failed")
end
return kong.request.get_body()
end
end
-- Helper function to check if a value is in a table
function contains(table, element)
for _, value in ipairs(table) do
if value == element then
return true
end
end
return false
end
return CustomHandler