You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenResty的Nginx中解码JWT访问令牌并记录sub字段?

Decoding Access Tokens for sub Field in OpenResty with openidc.lua

Got it, let's tackle this problem step by step. Since the openidc.lua module focuses on ID token handling by default, we can extend your OpenResty setup using the lua-resty-jwt library to decode access tokens, extract the sub field, and log it directly in Nginx.

Step 1: Install the Lua JWT Library

First, make sure you have the lua-resty-jwt library installed in your OpenResty environment. You can install it via OpenResty's package manager (opm):

opm install ledgetech/lua-resty-jwt

Step 2: Configure Nginx to Decode Access Tokens

Update your Nginx configuration to extract the access token from the Authorization header, decode it, pull the sub field, and log it. Here's a complete example:

http {
    # Add the path to the lua-resty-jwt library (adjust if your installation path differs)
    lua_package_path "/usr/local/openresty/site/lualib/resty/?.lua;;";

    server {
        listen 80;
        server_name your-app-domain.com;

        # Define a variable to store the decoded `sub` value
        set $jwt_sub "";

        location / {
            # Extract the access token from the Bearer Authorization header
            if ($http_authorization ~* "^Bearer (.+)$") {
                set $access_token $1;
            }

            # Lua block to decode the JWT and extract `sub`
            access_by_lua_block {
                local jwt = require "resty.jwt"
                
                # Replace this with your JWT verification secret/public key
                # For HS256: use your shared secret string
                # For RS256: load your public key file (example below)
                -- local secret = ngx.file.read("/path/to/your/public.key")
                local secret = "your-jwt-signing-secret"

                if ngx.var.access_token ~= "" then
                    -- Verify and decode the access token
                    local decoded_token = jwt:verify(secret, ngx.var.access_token)

                    if decoded_token.verified then
                        -- Extract the `sub` field from the JWT payload
                        local sub_value = decoded_token.payload.sub
                        ngx.var.jwt_sub = sub_value

                        -- Log the `sub` value immediately (optional)
                        ngx.log(ngx.INFO, "Authenticated user sub: ", sub_value)
                    else
                        -- Log verification failures for debugging
                        ngx.log(ngx.WARN, "Access token verification failed: ", decoded_token.reason)
                    end
                else
                    ngx.log(ngx.WARN, "No access token found in Authorization header")
                end
            }

            # Your existing reverse proxy configuration
            proxy_pass http://your-upstream-service;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        # Custom log format to include the `sub` field in access logs
        log_format extended '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "sub:$jwt_sub"';

        access_log /var/log/nginx/access.log extended;
    }
}

Key Notes to Keep in Mind

  • JWT Signing Algorithm: If your access tokens use asymmetric encryption (like RS256), replace the plain secret string with the content of your public key file (use ngx.file.read to load it, as commented in the example). For symmetric algorithms (HS256), just use your shared secret.
  • Error Handling: Adjust the logging or add HTTP responses (like returning 401 Unauthorized) based on token verification failures, depending on your application's requirements.
  • Compatibility with openidc.lua: This code can coexist with your existing openidc.lua setup. Just ensure the access_by_lua_block runs in the right order (you can combine both logic blocks if needed).

内容的提问来源于stack exchange,提问作者user9576045

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:20:01