Refactor auth.lua to enhance token handling with introspection, session support, and improved error handling.
This commit is contained in:
54
auth.lua
54
auth.lua
@@ -1,34 +1,52 @@
|
||||
local openidc = require("resty.openidc")
|
||||
|
||||
local client_secret = os.getenv("KEYCLOAK_CLIENT_SECRET")
|
||||
if not client_secret then
|
||||
ngx.log(ngx.ERR, "Missing KEYCLOAK_CLIENT_SECRET env variable")
|
||||
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
|
||||
end
|
||||
|
||||
local opts = {
|
||||
redirect_uri_path = "/redirect_uri",
|
||||
discovery = "https://kc.boomlab.party/realms/rhein-sw/.well-known/openid-configuration",
|
||||
client_id = "demo-sso",
|
||||
client_secret = client_secret,
|
||||
scope = "openid email profile",
|
||||
redirect_uri_scheme = "https",
|
||||
ssl_verify = "no"
|
||||
}
|
||||
|
||||
local res, err = openidc.authenticate(opts)
|
||||
-- Extract token from session or request
|
||||
local session = require("resty.session").start()
|
||||
local access_token = session.data.access_token
|
||||
|
||||
if err then
|
||||
ngx.status = 403
|
||||
ngx.say("Authentication failed: " .. err)
|
||||
ngx.exit(ngx.HTTP_FORBIDDEN)
|
||||
end
|
||||
|
||||
-- Check if token has expired
|
||||
if res.id_token and res.id_token.exp then
|
||||
local now = ngx.time()
|
||||
if res.id_token.exp < now then
|
||||
ngx.log(ngx.ERR, "Token expired")
|
||||
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
||||
if not access_token then
|
||||
-- fallback: try Authorization header
|
||||
local auth_header = ngx.var.http_Authorization
|
||||
if auth_header and auth_header:find("Bearer ") == 1 then
|
||||
access_token = auth_header:sub(8)
|
||||
end
|
||||
end
|
||||
|
||||
ngx.req.set_header("X-User", res.user.preferred_username or "")
|
||||
ngx.req.set_header("X-Email", res.user.email or "")
|
||||
if not access_token then
|
||||
ngx.status = 401
|
||||
ngx.say("Missing access token")
|
||||
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
||||
end
|
||||
|
||||
-- Introspect the token
|
||||
local res, err = openidc.introspect(opts, access_token)
|
||||
|
||||
if err then
|
||||
ngx.status = 403
|
||||
ngx.say("Token introspection failed: " .. err)
|
||||
ngx.exit(ngx.HTTP_FORBIDDEN)
|
||||
end
|
||||
|
||||
if not res.active then
|
||||
ngx.status = 401
|
||||
ngx.say("Session expired or revoked")
|
||||
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
||||
end
|
||||
|
||||
-- Optionally set headers for upstream
|
||||
ngx.req.set_header("X-User", res.username or "")
|
||||
ngx.req.set_header("X-Email", res.email or "")
|
||||
ngx.status = 204
|
||||
|
||||
Reference in New Issue
Block a user