...
Code Block | ||
---|---|---|
| ||
function main(Data)
-- Parse login GET Request for username and password
local request = net.http.parseRequest{data=Data}
local name = request.get_params.name
local pass = request.get_params.password
local success = false
-- validate username and password in KeyCloak
-- if success, log 1 and list of assigned roles.
success, roles = validateViaKeycloak(name, pass)
if success then
body = '1'
for _, role in pairs(roles) do
body = body .. '\r\n' .. role
end
else
body = '0'
end
local Response = net.http.respond{
body = body,
entity_type = "text/plain"
}
iguana.logInfo('Returning "' .. body .. '" for: ' .. name)
end
-- Authenticate user with KeyCloak
function validateViaKeycloak(name, pass)
local clientId = 'iguana'
local tokenURL = 'http://localhost:8080/realms/master/protocol/openid-connect/token'
local tokenRequest = net.http.post{
url = tokenURL,
headers = {['Content-Type']='application/x-www-form-urlencoded'},
parameters = {
['grant_type'] = 'password',
['client_id'] = clientId,
['username'] = name,
['password'] = pass
},
live=true
}
local response = json.parse{data=tokenRequest}
local token = response.access_token
-- If query succeeds, returns a valid token with user details, nil otherwise.
if token == nil then
return false
else
return true, getRoles(name, token)
end
end
function getRoles(name, token)
-- split and decode jwt payload containing user roles
local roles = {}
local jwt = token:split('.')
local payload = filter.base64.dec(jwt[2])
local payloadDetails = json.parse(payload)
local roles = payloadDetails.realm_access.roles
return roles
end |
...