When I researched adding single sign-on to legacy web applications, my original goal was simply to let users keep their bookmarks. One question took me from gateways into Lua and Python: once the gateway has received a request, where is the simplest place to check the user's session before forwarding it?
Built-in features and extension points: who handles a request?
When a user opens a bookmarked equipment page, the gateway has two jobs: determine whether to admit the user and forward the request to the asset system. Both Nginx and Traefik can forward requests. OpenResty provides places to run Lua during Nginx request processing.1 Python and Go can implement an authentication service called by a gateway, or implement the entire entry point. That choice determines which program subsequently handles even image and download traffic.23456
| Approach | Existing features and extension points | When it makes sense |
|---|---|---|
| Nginx + authentication service | proxy_pass forwards requests. With the auth_request module enabled, an authentication subrequest can run first. A 2xx admits the request, 401/403 deny it, and other statuses count as errors.2 | Nginx already manages domains and certificates, and the account system can decide admission. Retain the entry point and configure a separate redirect for unauthenticated browsers. |
| Traefik + authentication service | ForwardAuth continues forwarding after a 2xx and returns other responses to the client. The authentication service can therefore issue a login redirect itself. Routes can be discovered from Docker and other configuration sources.37 | Services change with container deployments, or Traefik already handles routing and several applications need shared authentication. Each actual call to the authentication service adds a round trip. |
| OpenResty + Lua | Run Lua before the request reaches the backend, validate a token or query Redis, and continue forwarding through Nginx. Small rules deploy with the gateway.849 | Decisions depend only on the current request or a session lookup, and the team can maintain Lua. This can eliminate a call to a separate auth service, though a Redis lookup still takes time. |
| Python + FastAPI | Expose only an auth endpoint and reuse Python account code. To handle all traffic, add an HTTP client, stream upstream responses back, and take care of closing connections.36 | Account, authorization, and audit rules already live in Python. Keeping the existing proxy avoids maintaining a second set of rules. Expand it into a custom proxy only when you need to handle application traffic itself. |
| Go + Gin or standard library | Gin middleware can run checks before business handlers. To have the same process forward requests, compose it with the standard library's httputil.ReverseProxy and implement backend selection and error handling.105 | You already run Go services or need to test and ship forwarding decisions with Go business logic. An auth-only endpoint can also sit behind Nginx or Traefik. |
| Kong + existing plugins | Enable plugins for selected routes, then send requests to the appropriate backend. Hanaasagi's introduction demonstrates adding a backend API and enabling a plugin.1112 | Existing plugins can verify your credentials and pass an identity the backend accepts, and the team can maintain Kong routes and plugins. |
The differences are clearest before login. Suppose the FastAPI auth endpoint returns a 302 redirect to the login page. Traefik's handling of this non-2xx response fits the requirement. Attach the same endpoint directly to Nginx's auth_request and the 302 is treated as a subrequest error. In the latter case the endpoint might return 401, with the gateway initiating the redirect. As Traefik's docs say, “The ForwardAuth middleware delegates authentication to an external service.” The account service can decide where to go next while the gateway still proxies the original equipment page.23
Why did Yichun Zhang value the combination of Nginx and Lua?
Before reading a Lua tutorial that day, I opened “From Copying Books to the Heights of Open Source: Yichun Zhang's Life in Programming.” Liumi's interview with Zhang offers some history. Zhang recalled rewriting OpenResty on Nginx and LuaJIT to serve data APIs for Taobao's Quantum Analytics, and later using it in Cloudflare's dynamic proxy system. The extension point was concrete: requests continued through a mature HTTP server, while developers could adapt the request-handling logic to their product.13
A few minutes later, I opened “OpenResty's Advantages Relative to Go.” Jinhailang quoted Zhang's words, “享受 NGINX 完整的基础设施和生态圈” (“benefit from NGINX's complete infrastructure and ecosystem”). He cited configuration reloads and hot binary upgrades and identified this as the OpenResty author's own perspective. For my use case, Hanaasagi supplied an especially clear example: validate a token inside access_by_lua, return 403 on failure, then forward successful requests with proxy_pass. Go can perform the same check. How much work that entails depends on who will maintain the proxy afterward.1485
How much Lua do a few lines of policy require?
I started with the JavaScript I knew. Weiting Dashixiong's tutorial gave an easily missed example: the number 0 in a Lua if takes the true branch. If an API represents failure with numeric zero and its result is used directly as the admission condition, the decision will be wrong. Another immediately relevant topic was loading libraries. Peace-4703 used Python's import fibo and Lua's require "complex" to load modules. With that in mind, require "resty.jwt" in the gateway configuration becomes clear: an existing library supplies token validation.15168
How does language popularity affect maintaining this rule?
On the cost of learning a language, Hanaasagi made a candid observation: “Golang 则还可以开发一些别的项目” (“Go can also be used to develop other projects”). After looking into Redis I opened several comparisons of Lua and Python. A Q&A republished by Tencent Cloud discussed their common uses: Python can implement standalone applications, while Lua is often embedded in an existing program to let users extend its particular behavior. In a Zhihu discussion about popularity, the respondent “无关紧要” cited Redis and OpenResty and linked to a website they made with Lua. I followed the link from the question later. Looking back, I may also have been wondering where else gateway scripting skills would be useful.81718
Stack Overflow's 2024 survey gives some indication of how many developers you might encounter who had used the languages. Among the 60,171 respondents who answered the language question, 51% had done extensive development work with Python in the preceding year, 13.5% with Go, and 6.2% with Lua. Respondents could choose multiple languages. The denominator is people who answered that question. Measuring how many services run Nginx, Traefik, or OpenResty requires different data.19
Communities also supply different kinds of help. In the popularity discussion, Kurapica noted that Lua libraries organize objects differently, complicating wrappers and editor completion. Dotblue valued the ready-to-use libraries in Python. Both observations tell me more about a technology choice than a popularity ranking. I'd list three things the team actually has to maintain: whether a library supports the identity provider, whether the gateway has a suitable plugin, and who can read the implementation when something fails. If account logic already lives in Python or Go, reusing libraries colleagues understand has a direct payoff. If existing Nginx configuration or Traefik middleware is sufficient, most maintainers won't even have to learn the proxy's implementation language.2023
What's the difference between accessing Redis from Lua and executing Lua in Redis?
That day, after reading the syntax and variables sections on Runoob, I searched for lua访问redis (“access Redis with Lua”) and opened a redis-lua client tutorial. For session checks, the distinction comes down to which process actually runs the script.
When OpenResty queries Redis, Lua runs inside the gateway. A script can issue a query through lua-resty-redis and use the result to decide whether to forward. The library example distinguishes a query error from a missing key: the former yields an error, the latter ngx.null. Neither establishes a valid login, but operations staff need to distinguish an expired or absent user session from temporary Redis unavailability.9
When Redis executes Lua, the application sends Redis a script, for example with EVAL, to perform a group of data operations atomically on the server. The result goes back to the caller, and the gateway still handles the HTTP request. If all you need is the value of a session key, a single ordinary query suffices.21
If Lua's integer loop is faster, will login requests be faster too?
In an answer to “Why Is Lua Faster Than Python?”, Liu Jin ran an integer loop in CPython 3.5.1 and examined the type dispatch, integer creation, and reference counting behind i += 1. He criticized estimating time by counting instructions, because different instructions do very different amounts of work. The experiment helps explain where that version of the interpreter spent time on local computation.22
Hanaasagi's experiment was closer to a gateway. In the 2017 write-up, wrk ran with two threads and 600 connections for 60 seconds. All four sets of requests carried a token, but the configurations did different work. These are the original requests-per-second figures. The Go configuration used Echo's proxy middleware.8
| 2017 configuration | Requests/sec | How to read the number |
|---|---|---|
| Nginx | 7,180.68 | Forwarding only. The output also recorded 106 timeouts. |
| OpenResty | 5,723.93 | Added Lua token validation before forwarding. |
| Traefik | 4,137.66 | Configured backend and forwarding rules, without external authentication. |
| Go / Echo | 3,475.66 | Round-robin proxy middleware inside the application, without equivalent token validation. |
These numbers help explain why the author wanted to keep exploring OpenResty. They don't measure Python, Gin, or today's versions. A meaningful comparison for my login scenario would have every option validate the same token, access the same session data, and record throughput, tail latency, and timeouts. Then I could judge whether removing a service call justified maintaining separate Lua logic.8
How would I divide responsibilities if we also had to manage and rotate passwords?
For legacy systems that accept only passwords, I'd keep the existing gateway and build an account service plus a rotation job that can run independently. Binding accounts, logging in on their behalf, and changing passwords use the same legacy application interfaces and belong in a shared, testable codebase. The scheduled job gets password-change permissions through its own runtime identity. The gateway handles sessions only. I'd use FastAPI for existing Python account code or reuse an existing Go implementation. Starting from scratch with a Python team, I'd pick Traefik + FastAPI because one auth response can express admission or redirect. If Nginx already manages the old domain, adding a subrequest and redirect requires less change.32
| What the user or system is doing | Who does the work | Does it read a password? |
|---|---|---|
| Binding a legacy account for the first time | The account service verifies ownership, calls the application's existing password-change interface, and stores a random password per account in a credential vault. | The original password is used only in the binding flow. |
| Opening another page while logged in | The gateway checks the entrance session, obtains the user's valid target-application session, and forwards with the corresponding cookie. | No. Pages, images, and downloads should not trigger password changes. |
| Entrance session is valid, but legacy session has expired | The account service retrieves the current password version, logs in again using the application's permitted flow, and saves the new session. Multiple tabs for the same user share one login result. | Only during reauthentication. The user completes additional verification if the application requires it. |
| Credentials reach their rotation date | The background job processes each legacy account serially, records a pending version, changes the password, verifies it, and promotes the version. On interruption, resume with the same pending version. Coordinate delegated logins during rotation to prevent repeated attempts with the old password. | The job reads and updates credentials as required.23 |
If a password change invalidates existing sessions, mark the corresponding mapping invalid after rotation. Also clear a session the first time the legacy application rejects it according to that application's expiration signals. A local expiration timestamp alone cannot detect an early logout. For binding, cookie storage, and recovery, see Single Sign-On Options for Legacy Applications.
How do the gateways admit the same logged-in request?
Consider only the bookmarked GET /devices/42. Assume the asset system requires one login cookie, maintained server-side per entrance session and application. On success, an internal check endpoint returns 204. Its response's Cookie field is for the gateway to copy into the outgoing request to the asset system. The browser's entrance cookie should not be forwarded verbatim. These forwarding snippets omit HTTPS, upstream definitions, and login callbacks. The account service handles the login path separately so it doesn't trigger the same check again.32
Traefik + FastAPI. Attach middleware to the same route. The request still goes to the asset service originally configured for it. Python handles only the session decision.3
http:
middlewares:
asset-session:
forwardAuth:
address: "http://accounts/check/assets"
authRequestHeaders: ["Cookie"]
authResponseHeaders: ["Cookie"]
@app.get("/check/assets")
async def check_assets(request: Request):
# 项目函数校验入口会话与应用访问权,再取服务端保存的旧会话。
cookie = await sessions.cookie_for(request.cookies.get("entry"), "assets")
if cookie is None:
return RedirectResponse(
"https://assets.example.com/_session/start?next=/devices/42",
status_code=302,
)
return Response(status_code=204, headers={"Cookie": cookie})
Here None means the user needs to log in or recreate the legacy session. Known lack of authorization returns 403, and the application's error handler returns 503 on storage failure. The example hardcodes the bookmark path to make the flow clear. The actual login service should store and validate local return paths. Production routes must distinguish APIs from browser navigation to avoid returning a login page to an API or automatically replaying a business write.
Nginx + the same account service. Reuse the session lookup above, but have the Nginx check endpoint return 401 when login is needed and let the gateway convert it to a redirect. The downstream cookie comes from the subrequest response.2
location = /devices/42 {
auth_request /_asset_check;
auth_request_set $asset_cookie $upstream_http_cookie;
error_page 401 =302 https://assets.example.com/_session/start?next=/devices/42;
proxy_set_header Cookie $asset_cookie;
proxy_pass http://assets_backend;
}
location = /_asset_check {
internal;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_pass http://accounts/check/assets-for-nginx;
}
OpenResty + Lua. If measurement shows significant per-request overhead from calling the account service, move just the session check into the gateway process. Here asset_sessions represents the project's own module, which must verify the entrance session, application permission, and the legacy session's expiration and revocation status. Login and password changes still go to the same account service.49
location = /devices/42 {
set $asset_cookie "";
access_by_lua_block {
local sessions = require "asset_sessions"
local cookie, reason = sessions.lookup(ngx.var.cookie_entry, "assets")
if reason == "login_required" then
return ngx.redirect("/_session/start?next=/devices/42", 302)
end
if reason == "forbidden" then return ngx.exit(403) end
if not cookie then return ngx.exit(503) end
ngx.var.asset_cookie = cookie
}
proxy_set_header Cookie $asset_cookie;
proxy_pass http://assets_backend;
}
Go can perform an equivalent in-process check. The success branch can lead straight to the standard-library reverse proxy. The upstream for assetsProxy is fixed to the asset system at startup. Gin middleware or an ordinary HTTP handler can handle login, refusal, and failure before taking this branch.510
// 位于已验证入口会话和应用权限的 handler 内。
upstreamRequest := r.Clone(r.Context())
upstreamRequest.Header.Set("Cookie", assetCookie)
assetsProxy.ServeHTTP(w, upstreamRequest)
These snippets assume the legacy session uses a fixed cookie while valid. If the legacy application refreshes its session cookie in ordinary responses, write that update back to the user's session mapping. For such an application, evaluate storing its own cookie in the browser under its original domain to reduce server-side adaptation.
Which wait does in-gateway validation remove from a request?
Suppose the user is logged in and clicks the original equipment bookmark again. The request to its original domain goes first to the gateway. Both implementations in the diagram query Redis once. With external authentication, the gateway asks the account service to perform the lookup and waits for its answer. With in-process validation the gateway queries Redis directly before forwarding the allowed request.
sequenceDiagram
actor U as 用户
participant B as 浏览器
participant G as 网关
participant A as 认证服务
participant R as Redis
participant S as 资产系统
U->>B: 点击设备页书签
B->>G: GET /devices/42(入口 Cookie)
alt 独立认证服务校验
G->>A: 检查会话
A->>R: 读取会话记录
R-->>A: 会话记录
A-->>G: 放行,附旧应用 Cookie
else 网关内联校验
G->>R: 读取会话记录
R-->>G: 会话记录
Note over G: 本地校验,取出旧应用 Cookie
end
G->>S: GET /devices/42(旧应用 Cookie)
S-->>G: 返回设备页
G-->>B: 转发设备页
B-->>U: 显示设备页
I'd start with the external authentication scheme that's easier to maintain. During load testing, record how long the gateway waits for the authentication service and how much of that time is spent querying Redis. If Redis dominates, moving the same query into the gateway still means waiting for Redis. If the gateway-to-auth round trip already affects page latency, test in-process OpenResty or Go validation with the same traffic. If the gateway also caches results, compare options against the same session revocation deadline.
Measure legacy-application response times separately for initial login and session reconstruction. Keep password rotation in the background job and track whether it finishes on schedule under the legacy application's rate limits. The 2017 benchmark covered none of these flows.
References
Footnotes
-
liwang2019. (2011, June 21). Components, Nginx, LuaNginxModule, and LuaJIT. OpenResty.org. Updated August 20, 2026. ↩
-
NGINX. (n.d.). Module ngx_http_auth_request_module, module introduction and configuration example. nginx.org. https://nginx.org/en/docs/http/ngx_http_auth_request_module.html ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7
-
Traefik Labs. (n.d.). ForwardAuth, v3.3, first paragraph under “Using an External Service to Forward Authentication.” Traefik Proxy documentation. https://doc.traefik.io/traefik/v3.3/middlewares/http/forwardauth/#forwardauth ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8
-
OpenResty. (n.d.). OpenResty, platform introduction, paragraphs 1–3. OpenResty.org. https://openresty.org/en/ ↩ ↩2 ↩3
-
The Go Authors. (n.d.). Package httputil (ReverseProxy). Go Packages. https://pkg.go.dev/net/http/httputil#ReverseProxy ↩ ↩2 ↩3 ↩4
-
Encode. (n.d.). Async support, streaming responses. HTTPX documentation. https://www.python-httpx.org/async/#streaming-responses ↩ ↩2
-
Traefik Labs. (n.d.). Configuration discovery, Providers, v3.3. Traefik Proxy documentation. https://doc.traefik.io/traefik/v3.3/providers/overview/ ↩
-
Hanaasagi. (2017, July 21). OpenResty Worst Practices, four forwarding tests, conclusion after the Echo test, and configurations at the end. Hanaasagi's Blog. https://blog.dreamfever.me/posts/2017-07-21-openresty-zui-chai-shi-jian/ ↩ ↩2 ↩3 ↩4 ↩5 ↩6
-
OpenResty. (n.d.). lua-resty-redis, Description and GET example in Synopsis. GitHub. https://github.com/openresty/lua-resty-redis#synopsis ↩ ↩2 ↩3
-
Gin. (n.d.). Middleware, “How middleware works.” Gin Web Framework. https://gin-gonic.com/en/docs/middleware/#how-middleware-works ↩ ↩2
-
Kong. (n.d.). Routes, “What is a Route?” Kong Docs. https://developer.konghq.com/gateway/entities/route/#what-is-a-route ↩
-
Hanaasagi. (2017, July 16). Kong: From Getting Started to Getting Caught in the Door, “Adding an API” and “Enabling Plugins” in “Basic Kong Operations.” Hanaasagi's Blog. https://blog.dreamfever.me/posts/2017-07-16-kong-cong-ru-men-dao-bei-men-ji/ ↩
-
Liumi (interviewer), Liumi and Yingzi (editors). (n.d.). From Copying Books to the Heights of Open Source: Yichun Zhang's Life in Programming [interview]. Turing Community. Original publication, Zhihu page I opened, Nginx and LuaJIT passage in a reprint. ↩
-
jinhailang. (2018, May 30). OpenResty's Advantages Relative to Go [issue #20, quoting Yichun Zhang's discussion, point 2 and final paragraph]. GitHub. https://github.com/jinhailang/blog/issues/20 ↩
-
Weiting Dashixiong. (n.d.). A Quick Introduction to Lua for JavaScript Developers, conditional example in section 3. Zhihu. https://zhuanlan.zhihu.com/p/619501046 ↩
-
Peace-4703. (2016, September 30). Learning Python and Lua: A Comparison, Part Five, sections on declaring and using modules. CSDN. https://blog.csdn.net/glp3329/article/details/52713288 ↩
-
BenjaminB. (2011, April 8). Why Python and not Lua? Software Engineering Stack Exchange. I visited the Tencent Cloud Chinese Q&A. For embedded scripting and general-purpose programming, see Klaim's answer that day. ↩
-
无关紧要. (2019, October 6). Why Does Lua Seem Less Popular Than Python? [answer, paragraphs 2–4, on Redis, OpenResty, and a Lua website]. Zhihu. Examples in the answer. ↩
-
Stack Overflow. (2024). 2024 Developer Survey: Technology, Most popular technologies → Programming, scripting, and markup languages → All Respondents. https://survey.stackoverflow.co/2024/technology/#1-programming-scripting-and-markup-languages ↩
-
Kurapica. (2018, April 19, edited). Why Does Lua Seem Less Popular Than Python? [answer, paragraphs 1–2]. Zhihu. Library reuse and host scenarios. dotblue. (2020, March 9, edited). Answer to the same question, paragraphs 2–4. Zhihu. Library support. ↩
-
Redis. (n.d.). Scripting with Lua, “Executing Lua in Redis.” Redis Docs. https://redis.io/docs/latest/develop/programmability/eval-intro/ ↩
-
Liu Jin. (2016, June 19, edited). Why Is Lua Faster Than Python? [answer, point 2 after the discussion of the Python loop body]. Zhihu. Integer loop analysis. ↩
-
Amazon Web Services. (n.d.). Lambda rotation functions, four steps in a rotation function. AWS Secrets Manager User Guide. https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_lambda-functions.html ↩