首页 > 解决方案 > Kubernetes 入口自定义 JWT 身份验证缓存密钥

问题描述

我们将 Kubernetes 入口与外部服务JWT 身份验证一起auth-url用作入口的一部分。

现在我们要使用auth-cache-key注解来控制 JWT 令牌的缓存。目前,我们的外部身份验证服务只是通过查看令牌来响应200/ 。401我们所有的组件都是带有rest api的后端微服务。传入的请求可能不是 UI 请求。我们如何为传入的 JWT 令牌填写“auth-cache-key”。

  annotations:
    nginx.ingress.kubernetes.io/auth-url: http://auth-service/validate
    nginx.ingress.kubernetes.io/auth-response-headers: "authorization"
    nginx.ingress.kubernetes.io/auth-cache-key: '$remote_user$http_authorization'
    nginx.ingress.kubernetes.io/auth-cache-duration: '1m'
    kubernetes.io/ingress.class: "nginx"

看例子,$remote_user$http_authorization在K8s文档中被指定为例子。但是不确定是否$remote_user会在我们的案例中设置。因为这不是外部基本身份验证。在这种情况下,我们如何决定 auth 缓存键?

这方面没有足够的示例/文档。

标签: authenticationkubernetesingress-nginx

解决方案


发布一般答案,因为没有提供进一步的细节和解释。

确实没有那么多文档,所以我决定深入研究 NGINX Ingress 源代码

注释中设置的值是代码nginx.ingress.kubernetes.io/auth-cache-key中的变量:$externalAuth.AuthCacheKey

{{ if $externalAuth.AuthCacheKey }}
set $tmp_cache_key '{{ $server.Hostname }}{{ $authPath }}{{ $externalAuth.AuthCacheKey }}';
set $cache_key '';

可以看到,$externalAuth.AuthCacheKey由 variable 使用$tmp_cache_key,它被编码为base64格式并$cache_key使用lua NGINX 模块设置为变量:

rewrite_by_lua_block {
    ngx.var.cache_key = ngx.encode_base64(ngx.sha1_bin(ngx.var.tmp_cache_key))
}

然后$cache_key用于设置定义缓存键的变量$proxy_cache_key

proxy_cache_key "$cache_key";

基于上面的代码,我们可以假设我们可以使用任何NGINX 变量来设置nginx.ingress.kubernetes.io/auth-cache-key注解。请注意,有些变量只有在加载了相应的模块时才可用。

示例 - 我设置了以下auth-cache-key注释:

nginx.ingress.kubernetes.io/auth-cache-key: '$proxy_host$request_uri'

然后,在 NGINX Ingress 控制器 pod 上,文件/etc/nginx/nginx.conf中有以下行:

set $tmp_cache_key '{my-host}/_external-auth-Lw-Prefix$proxy_host$request_uri';

如果将auth-cache-key注解设置为不存在的 NGINX 变量,NGINX 将抛出以下错误:

nginx: [emerg] unknown "nonexistent_variable" variable

这取决于您需要哪些变量。

请同时查看以下文章和主题:


推荐阅读