代码之家  ›  专栏  ›  技术社区  ›  Roman Rastiehaiev

Nginx在error_page中返回动态JSON响应

  •  0
  • Roman Rastiehaiev  · 技术社区  · 2 年前

    我有两个REST应用程序:主API和Auth API。我在上面配置了Nginx,这样请求就首先到达auth API,如果auth成功,则在主API中继续。

    当Auth API返回401或403时,我想将错误代码作为JSON返回给客户端作为响应。然而,正如我在谷歌上搜索的那样,Nginx不支持将响应体从 auth_request .所以我想我可以将Auth API中的错误代码设置为响应头,并使用 error_page 指令。这是我的Nginx配置:

    server {
        listen       80;
        server_name  127.0.0.1;
    
        if_modified_since off;
        expires off;
        etag off;
    
        set $api_base_url "http://api:9090";
        set $service_user_base_url "http://auth-api:9091";
    
        resolver 127.0.0.11 ipv6=off;
    
        location /some-api-endpoint {
            auth_request /validate_token;
            auth_request_set $authorization $upstream_http_authorization;
    
            proxy_pass $api_base_url;
            proxy_intercept_errors on;
            add_header Authorization $authorization;
    
            error_page 401 = @handle_auth_401;
            error_page 403 = @handle_auth_403;
        }
    
        location = /validate_token {
            internal;
            if ($request_method = OPTIONS) {
                return 200;
            }
            proxy_pass  $service_user_base_url/validation;
            proxy_pass_request_body off;
            proxy_set_header X-Original-URI $request_uri;
            proxy_set_header X-Original-Method $request_method;
        }
    
        location @handle_auth_401 {
            default_type application/json;
            return 401 '{"failure":{"type":"$upstream_http_x_auth_failed_error_code"}}';
        }
    
        location @handle_auth_403 {
            default_type application/json;
            return 403 '{"failure":{"type":"$upstream_http_x_auth_failed_error_code"}}';
        }
    }
    

    然而,我收到的回复是 {"failure":{"type":""}} .当我调用auth API的 /validation 端点,我收到了标头“X-Auth-Failed-Error-Code”作为响应,但由于某种原因,Nginx无法解决它。似乎我错过了什么。

    以前有人尝试过这种方法或遇到过同样的问题吗?非常感谢您的帮助。

    UPD :

    好的,我已经设法解决了这个问题,使用另一个 auth_request_set API位置中的指令:

        location /some-api-endpoint {
            auth_request /validate_token;
            auth_request_set $authorization $upstream_http_authorization;
            auth_request_set $x_auth_failed_error_code $sent_http_x_auth_failed_error_code;
    ...
    

    然后我在命名位置使用新变量,如下所示:

        location @handle_auth_401 {
            default_type application/json;
            return 401 '{"failure":{"type":"$x_auth_failed_error_code"}}';
        }
    
    0 回复  |  直到 2 年前
    推荐文章