缓存 nginx auth_request

sup*_*tor 7 nginx

我正在尝试配置一个 nginx1.12.2反向代理以使用auth_requestproxy_cache验证对微服务的请求。最终用户Bearer随他们的请求发送一个简单的令牌,服务器尝试用它获取资源以确定是否允许他们继续。应该为给定的令牌缓存该资源获取,以减轻身份验证端点的负载。到目前为止,这是我的配置:

ssl_certificate                 /etc/nginx/ssl/certificate;
ssl_certificate_key             /etc/nginx/ssl/key;
proxy_cache_path                /var/cache/nginx/auth_cache levels=1:2 keys_zone=auth_cache:1m max_size=1g inactive=60m;
server {
    listen                      80;
    listen                      443 ssl;
    server_name                 myapi.mydomain.com;
    location / {
        proxy_pass              http://myapi/;
        auth_request            /auth;
    }
    location = /auth {
        internal;
        proxy_pass              https://authendpoint.mydomain.com/api/user/verify;
        proxy_cache             auth_cache;
        proxy_cache_key         "$http_x_auth_token$request_uri";            
        proxy_pass_request_body off;
        proxy_set_header        Content-Length "";
        proxy_set_header        X-Original-URI $request_uri;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
Run Code Online (Sandbox Code Playgroud)

从客户端的角度来看,这很好用,但是当我查看 nginx 服务器时,没有任何内容写入缓存文件夹。该文件夹已/var/cache/nginx/auth_cache创建,但始终为空。我可能会错过什么?

更新

使用较新的 nginx(1.17.9目前)尝试此操作,我们仍然看不到任何写入缓存文件夹的内容。在其他地方,我看到了 cookie 可以阻止缓存的建议 - 这个应用程序不使用 cookie,但我们还是尝试了:

location = /auth {
    internal;
    proxy_pass              http://authservice/api/user/verify;
    proxy_cache             auth_cache;
    proxy_cache_key         "$http_x_auth_token$request_uri";   
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        X-Original-URI $request_uri;
    proxy_hide_header       Set-Cookie;
    proxy_ignore_headers    Set-Cookie;
    proxy_set_header        Cookie "";
}
Run Code Online (Sandbox Code Playgroud)

还是一样的行为;auth_cache 文件夹已创建,但那里没有写入任何内容,并且不会缓存对我们的 auth 端点的请求。

仅供参考,我们的 auth 端点的结果非常少:

< HTTP/1.1 200 OK
< Date: Sun, 12 Apr 2020 18:04:08 GMT
< Server: Kestrel
< Content-Length: 0

Run Code Online (Sandbox Code Playgroud)

自从我最初提出这个问题以来,我们还简化了远程身份验证端点。现在,它是http在与 nginx 进程相同的集群中运行的普通资源。我已经更新了上面的例子来反映这一点。

最后更新

万一其他人尝试使用它作为参考,除了下面两个有用的答案之外,我们还需要修复上面示例中的缓存键:

proxy_cache_key         "$http_x_auth_token$request_uri";            
Run Code Online (Sandbox Code Playgroud)

仅当您实际X-Auth-Token用作标题时才有意义,而不仅仅是Authorization. 上面的键可以工作,但这意味着任何 uri 的第一个代理身份验证响应都将被缓存,而实际的令牌将被忽略。真的,我们需要:

proxy_cache_key         "$http_authorization$request_uri";            
Run Code Online (Sandbox Code Playgroud)

小智 2

尝试升级 NGINX。

我在 1.14.0 中遇到了同样的问题,其中使用curl对 /auth 的手动请求被缓存,但 auth_request 子请求没有被缓存。

升级到 NGINX 1.16.1 后它开始工作。