基于上游的状态码触发 openidc 认证

我正在使用 lua-resty-openidc 实现一个 web UI,该 UI 位于后端系统前面。

后端提供了一个受 JWT 保护的 REST API,包含在 Authorization 头中。前端管理会话,并在需要登录时将 Web 用户发送到身份提供程序。当 Web 用户拥有会话时,前端必须查找 JWT,将其添加到 Authorization 标头中,并代理对后端的请求 - 这是相当标准的做法。

不幸的是,我的后端没有明确区分公共资源和私有资源。例如,它可能有以下 URL 的资源:

  • /api/public/0
  • /api/public/1
  • /api/private/2
  • /api/private/3

它允许请求 /api/public/{0,1} 不带 Authorization 头,但 /api/private/{2,3} 需要授权。前端必须以某种方式处理此问题。(注意:以上 URL 简化了,真实的 URL 没有遵循一定的模式,不能很容易地枚举)

核心问题在于 _前端无法根据请求 URI 判断是否应该触发登录_。它必须是反应式的,将请求代理到后端并检查响应代码。401 码应该强制客户端登录,但任何其他响应应该按原样返回。

因此,我无法将我的身份验证逻辑放入 access_by_lua 块中,因为它们在请求被发送到上游(后端)之前运行在 访问阶段 中。

我尝试使用 body_filter_by_lua 块将我的逻辑移入 content 阶段 中:

location /api {
  set $session_storage shm;
  proxy_set_header X-Forwarded-Host  $http_host;
  proxy_pass https://backend;

  body_filter_by_lua_block {
    if ngx.status == ngx.HTTP_UNAUTHORIZED then
      ngx.log(ngx.INFO, 'Upstream returned a 401! Triggering auth flow')

      local opts = {
        discovery = 'https://login-server/.well-known/openid-configuration',
        scope = 'openid',
      }

      local res, err = openidc.authenticate(opts)
      if err or not res then
        ngx.status = ngx.HTTP_UNAUTHORIZED
        ngx.header.content_type = 'text/html';
        ngx.log(ngx.ERR, err)
        ngx.say("Forbidden")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
      end

    end
  }
}

… 但是它会出现错误(如下所示)。看起来我太晚进入请求处理周期以设置头和 cookie:

*194 [lua] body_filter_by_lua:5: Upstream returned a 401! Triggering auth flow while sending to client, client: 10.255.1.2, server: , request: "GET /api/private/2 HTTP/1.1", upstream: "https://backend/api/private/2", host: "frontend.example.org"

*194 [lua] openidc.lua:1363: authenticate(): Error starting session: Attempt to set session cookie after sending out response headers. while sending to client, client: 10.255.1.2, server: , request: "GET /api/private/2 HTTP/1.1", upstream: "https://backend/api/private/2", host: "frontend.example.org"

*194 attempt to set ngx.status after sending out response headers while sending to client, client: 10.255.1.2, server: , request: "GET /api/private/2 HTTP/1.1", upstream: "https://backend/api/private/2", host: "frontend.example.org"

是否可能在 Nginx 请求处理的 content 阶段 中执行 openidc.authenticate()

是否有更好的方法可以使用?

点赞
用户3394770
用户3394770

我最终调整了后端中使用的 URL 模式,以便提前区分私有和公共 URL。然后前端逻辑变得简单:

  • 请求公共资源:代理到后端
  • 请求私有资源,无 Authorization 标头:返回 401
  • 请求私有资源,有授权头:代理到后端

我不知道在 OpenResty 中是否可能采取原始问题(首先代理,然后根据响应代码做出决策)。但最终我认为新方法更清洁。

2020-11-30 14:47:57