Adding Authentication to Kubernetes Admin UIs with an nginx Sidecar
Document information
Section titled âDocument informationâ| Item | Details |
|---|---|
| Purpose | Add authentication to admin UIs that have no login, without modifying the applications |
| Targets | NATS NUI (Helm chart, StatefulSet), Valkey Admin (hand-written Deployment) |
| Tooling | Kustomize (helmCharts, configMapGenerator, JSON 6902 patch, strategic merge patch) |
| Entry point | Gateway API HTTPRoute (Envoy Gateway). The setup itself does not depend on the Ingress Controller type |
| Verification scope | Manifest configuration and rendering. Post-deployment behavior is verified separately with the checklist below |
Background
Section titled âBackgroundâWhen you operate a message broker or a cache, you eventually need an admin UI to inspect the data. The two tools added here are:
- NATS NUI: a Web UI for NATS subjects, JetStream streams, and KV. It has an official Helm chart.
- Valkey Admin: a Web UI for Valkey (Redis-compatible) keys and metrics. It has no official Helm chart, so the Deployment was written by hand from the upstream Docker documentation.
Neither tool has its own login. Anyone who can reach the URL can publish messages or delete keys. Backend credentials (NATS credentials, the Valkey password) are already inside the Pod, so access to the UI is access to the data.
Where to put authentication
Section titled âWhere to put authenticationâThere were three options.
| Location | Approach | Problem in this environment |
|---|---|---|
| Entry point (Gateway/Ingress) | Basic Auth in an Envoy Gateway SecurityPolicy, NGINX Ingress auth-* annotations, and so on | Configuration differs per controller. The same manifests cannot be carried as-is to environments with a different entry point |
| Application | The appâs own login feature | Neither tool has one |
| Sidecar in the Pod | nginx authenticates with auth_basic and forwards to the app on 127.0.0.1 | Apart from a slightly more complex Pod spec, it is independent of the controller |
This setup assumes deployments where the Ingress/Gateway Controller may differ from site to site. That is why authentication is attached to the workload with a Sidecar. The HTTPRoute knows nothing about authentication and keeps pointing at the Service as before.
Entry-point policies such as IP allowlists are covered in Envoy Gateway Setup. The two approaches are not mutually exclusive: the entry-point policy checks âwhere the request comes fromâ, and the Sidecar checks âwho is making itâ.
Request flow
Section titled âRequest flowâTwo points matter.
- Only the Service targetPort changes. The Service
portand the HTTPRoutebackendRefsstay the same;targetPortmoves from the app port to the Sidecarâsauth-http. Nothing on the entry-point side changes. - Bind the app to loopback where possible. If the app listens on
0.0.0.0, a client can skip the Service and reach the app port on the Pod IP directly, bypassing authentication.
nginx configuration
Section titled ânginx configurationâThe nginx configuration has the same structure for both UIs. The one below is for Valkey Admin.
# Basic auth proxy (sidecar) in front of the app.# readOnlyRootFilesystem is enabled, so pid/temp paths go to emptyDir (/tmp).worker_processes 1;pid /tmp/nginx.pid;error_log /dev/stderr warn;
events { worker_connections 1024;}
http { access_log /dev/stdout; client_body_temp_path /tmp/client_temp; proxy_temp_path /tmp/proxy_temp; fastcgi_temp_path /tmp/fastcgi_temp; uwsgi_temp_path /tmp/uwsgi_temp; scgi_temp_path /tmp/scgi_temp;
# The UI talks to its server over websocket. map $http_upgrade $connection_upgrade { default upgrade; '' close; }
server { listen 8081;
# readiness: ready only when the app responds location = /healthz { auth_basic off; access_log off; proxy_pass http://127.0.0.1:8080/; }
location / { auth_basic "Authentication Required - valkey-admin"; auth_basic_user_file /etc/nginx/auth/auth;
proxy_pass http://127.0.0.1:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_buffering off; proxy_read_timeout 3600s; proxy_send_timeout 3600s; } }}Each setting has a reason.
- Temp and pid paths move to
/tmp. The container runs withreadOnlyRootFilesystem: true, so nginx cannot write to its default paths (/var/run,/var/cache/nginx).emptyDirvolumes are mounted at/tmpand/var/cache/nginx. - WebSocket upgrades are forwarded. NUI exchanges NATS messages over
/ws, and Valkey Admin also talks to its server over WebSocket. Withoutproxy_http_version 1.1and theUpgrade/Connectionheaders, the page opens but no data arrives. Timeouts are raised to one hour so long-lived connections are not cut, andproxy_buffering offis used for streaming responses. - The
Hostheader is passed through. Valkey Admin accepts a WebSocket connection only when the requestâsOriginandHostmatch. With the nginx default ($proxy_host, here127.0.0.1:8080),HostandOrigindiffer and the WebSocket is rejected. /healthzis exempt from authentication. kubelet probes do not send credentials.
Static healthz or proxied to the app
Section titled âStatic healthz or proxied to the appâThe two UIs intentionally use different /healthz setups.
| UI | /healthz | Reason |
|---|---|---|
| NATS NUI | return 200 "ok\n"; (answered by nginx) | The chart already sets httpGet / liveness and readiness probes on the app port (http, 31311). Those cover app health; the Sidecar probe only checks that nginx is alive |
| Valkey Admin | proxy_pass http://127.0.0.1:8080/; | The app binds only to 127.0.0.1, so kubelet probes cannot reach it. The app probe is removed, and the Sidecarâs /healthz also checks the app response |
If you use only a static response and have no app probe, the Pod stays Ready even when the app is dead. Conversely, the fact that a kubelet probe succeeds directly against the app port, as with NUI, also means the app is listening on the Pod IP. This comes back in the limitations below.
A UI deployed from a Helm chart: NATS NUI
Section titled âA UI deployed from a Helm chart: NATS NUIâNUI renders the official chart through Kustomize helmCharts and layers patches on the output. There is no chart fork, so chart upgrades stay easy.
namespace: tools
resources:- ./httproute.yaml
helmCharts:- name: nui version: 0.1.6 releaseName: nats-nui namespace: tools valuesFile: values.yaml
# Generate a ConfigMap from nginx.conf.# The name is fixed so it matches the volume reference in the patch.configMapGenerator:- name: nats-nui-auth-proxy files: - nginx.conf=auth-proxy.conf options: disableNameSuffixHash: true
patches:# Add the auth-proxy container and volumes to the StatefulSet- target: group: apps version: v1 kind: StatefulSet name: nats-nui path: auth-proxy-patch.yaml# Send the Service to auth-proxy instead of NUI. The HTTPRoute still points at the Service port.- target: version: v1 kind: Service name: nats-nui patch: |- - op: test path: /spec/ports/0/targetPort value: 31311 - op: replace path: /spec/ports/0/targetPort value: auth-httpThe op: test in the Service patch is a safety net. If a chart upgrade changes the port order or the targetPort value, the build fails at render time instead of letting replace overwrite the wrong port. A stopped build is better than an authentication path that breaks silently.
disableNameSuffixHash: true has a cost. Without a hash suffix, changing nginx.conf does not change the Pod template, so no rolling restart happens. After a configuration change, run kubectl rollout restart as well, or put a configuration hash into a Pod template annotation.
The StatefulSet patch appends the container and volumes to the arrays with JSON 6902 add.
- op: add path: /spec/template/spec/containers/- value: name: auth-proxy image: registry.example.io/library/nginx:<version> imagePullPolicy: IfNotPresent # docker-entrypoint.sh tries to modify /etc/nginx, so skip it and run nginx directly. command: ["nginx", "-g", "daemon off;"] ports: - name: auth-http containerPort: 8080 protocol: TCP readinessProbe: httpGet: path: /healthz port: auth-http livenessProbe: httpGet: path: /healthz port: auth-http resources: requests: cpu: 10m memory: 16Mi limits: memory: 64Mi securityContext: runAsNonRoot: true runAsUser: 101 runAsGroup: 101 allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL seccompProfile: type: RuntimeDefault volumeMounts: - name: auth-proxy-conf mountPath: /etc/nginx/nginx.conf subPath: nginx.conf readOnly: true - name: auth-proxy-htpasswd mountPath: /etc/nginx/auth readOnly: true - name: auth-proxy-tmp mountPath: /tmp - name: auth-proxy-cache mountPath: /var/cache/nginx- op: add path: /spec/template/spec/volumes/- value: name: auth-proxy-conf configMap: name: nats-nui-auth-proxy- op: add path: /spec/template/spec/volumes/- value: name: auth-proxy-htpasswd secret: secretName: nats-nui-basic-auth- op: add path: /spec/template/spec/volumes/- value: name: auth-proxy-tmp emptyDir: {}- op: add path: /spec/template/spec/volumes/- value: name: auth-proxy-cache emptyDir: {}Points worth noting in the container settings:
- The entrypoint is bypassed. The official nginx imageâs
docker-entrypoint.shtries to generate or modify configuration under/etc/nginxat startup. That fails on a read-only root filesystem, songinx -g "daemon off;"runs directly. - It runs as UID 101. This is the
nginxuser in the official image. Using ports above 1024, such as 8080 and 8081, lets every capability be dropped withoutNET_BIND_SERVICE. - Only
nginx.confis mounted withsubPath./etc/nginxis not overwritten as a whole by the ConfigMap, so files shipped in the image such asmime.typesstill work. On the other hand, asubPathmount does not pick up ConfigMap changes in a running container, which is another reason the restart above is needed.
A hand-written UI: Valkey Admin
Section titled âA hand-written UI: Valkey AdminâThe base Deployment for Valkey Admin is hand-written, so the Sidecar fits naturally into a strategic merge patch. Here the setup goes one step further than NUI and binds the app to loopback only.
# The app binds only to 127.0.0.1:8080 (no direct access from outside the pod),# and auth-proxy (nginx, 8081) forwards after basic auth.apiVersion: apps/v1kind: Deploymentmetadata: name: valkey-adminspec: template: spec: containers: - name: valkey-admin env: - name: SERVER_BIND_HOST value: 127.0.0.1 - name: VALKEY_HOST value: valkey.tools.svc.cluster.local - name: VALKEY_PORT value: "6379" - name: VALKEY_AUTH_TYPE value: password - name: VALKEY_USERNAME value: default - name: VALKEY_PASSWORD valueFrom: secretKeyRef: name: valkey-auth key: default # With a 127.0.0.1 bind, kubelet probes cannot reach the app, # so the app probe is removed and auth-proxy /healthz checks the app. readinessProbe: null - name: auth-proxy image: registry.example.io/library/nginx:<version> command: ["nginx", "-g", "daemon off;"] ports: - name: auth-http containerPort: 8081 protocol: TCP readinessProbe: httpGet: path: /healthz port: auth-http # resources, securityContext and volumeMounts are the same as NUI. volumes: - name: auth-proxy-conf configMap: name: valkey-admin-auth-proxy - name: auth-proxy-htpasswd secret: secretName: valkey-admin-basic-auth - name: auth-proxy-tmp emptyDir: {} - name: auth-proxy-cache emptyDir: {}---# patches-service.yamlapiVersion: v1kind: Servicemetadata: name: valkey-adminspec: ports: - name: http port: 80 targetPort: auth-http- Containers in the same Pod share a network namespace. nginx reaches the app at
127.0.0.1:8080, but nothing outside the Pod can reach<pod-ip>:8080. The path that skips the Sidecar disappears structurally. - The probe is deleted with
null. In a strategic merge patch,nullremoves the basereadinessProbe. When the app port is open only on loopback, a kubelet TCP probe can only fail. - The app port 8080 and the Sidecar port 8081 are separate. Two processes in the same network namespace cannot use the same port. NUIâs Sidecar could use 8080 only because NUIâs app port is 31311.
htpasswd Secret
Section titled âhtpasswd SecretâThe Secret holds a single htpasswd line (user:hash) under the auth key. nginx reads it from /etc/nginx/auth/auth. The value itself is not committed to the GitOps repository; only an example file lives in the repository, and the real Secret is created separately before deployment.
# nats-nui-basic-auth.secret.yaml.example# The value is one htpasswd line (user:hash). bcrypt (htpasswd -nB) or {SHA}.apiVersion: v1kind: Secretmetadata: name: nats-nui-basic-auth namespace: toolstype: OpaquestringData: auth: REPLACE_ME# Create the Secret with a bcrypt hash (the password is entered at the prompt)htpasswd -nB <user> > authkubectl -n tools create secret generic nats-nui-basic-auth --from-file=auth=authrm authThe hash format needs checking. nginx verifies hashes in auth_basic_user_file with the system crypt(), and additionally supports {PLAIN}, {SHA}, and {SSHA}. Whether bcrypt ($2y$) works depends on the libc crypt() implementation in the image, so confirm it with a real login on the nginx image you use. {SHA} is unsalted SHA-1 and is not safe. Bcrypt, on the other hand, recomputes the hash on every request, so on a busy UI the Sidecarâs CPU usage grows with the cost value. The 10m CPU request in this setup assumes an admin UI with few users.
What this setup does not prevent
Section titled âWhat this setup does not preventâA Basic Auth Sidecar only turns âa UI anyone can openâ into âa UI only people with the credential can openâ. Operators should know these limits.
- Without TLS, credentials travel in clear text. The Basic Auth header is only base64-encoded. The HTTPRoute in this setup is attached to the Gatewayâs
httplistener, so unless the UI is internal-only, an HTTPS listener or TLS termination in front is required. - If the app listens on the Pod IP, an in-cluster bypass is possible. NUIâs bind address was not changed, and the chartâs kubelet probes succeed directly against the app port. Assume that other Pods in the cluster can reach
<pod-ip>:31311without going through the Sidecar. If the appâs bind address cannot be changed, block ingress to the app port with a NetworkPolicy. This setup does not have that NetworkPolicy yet. - There is no per-user identity or permission split. With one shared account, nothing records who did what, and read-only access cannot be granted. When people leave or responsibilities change, the Secret has to be rotated and the Pod restarted. If SSO or RBAC is needed, move to OAuth2 Proxy or an OIDC policy at the entry point.
- There is no brute-force protection. Consider nginx
limit_reqor an entry-point rate limit as well. - Without the Secret, the Pod does not start. The Secret volume is not
optional, so deploying before creating the Secret leaves the Pod inContainerCreating. That is a safer failure than starting without authentication by accident.
What to check after deployment
Section titled âWhat to check after deploymentâThe items below are a checklist to run in the deployed environment. A successful manifest render does not mean authentication works.
# Render output: is the Service targetPort now auth-http?kustomize build --enable-helm <overlay>/nats-nui | grep -A6 'kind: Service'
# Are both containers Ready?kubectl -n tools get pod -l app=valkey-adminkubectl -n tools describe pod <pod> | grep -A3 'auth-proxy'
# Without credentials the response must be 401curl -s -o /dev/null -w '%{http_code}\n' https://<ui-host>/
# With credentials, 200curl -s -o /dev/null -w '%{http_code}\n' -u <user> https://<ui-host>/
# Bypass path: is direct access to the app port from another Pod blocked?kubectl -n tools run probe --rm -it --image=curlimages/curl --restart=Never -- \ curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://<pod-ip>:<app-port>/For the last item, expect a connection failure for Valkey Admin and, without a NetworkPolicy, a 200 for NUI. That result is the basis for deciding whether the bypass path has to be closed. In a browser, confirm that data actually updates after login; only that verifies WebSocket forwarding.
Summary
Section titled âSummaryâ| Decision | Reason |
|---|---|
| Authenticate inside the Pod, not at the entry point | The same manifests work regardless of the Ingress/Gateway Controller |
Switch only the Service targetPort to the Sidecar | The HTTPRoute and Service port stay unchanged |
JSON 6902 op: test | When the chart changes, rendering fails instead of silently patching the wrong field |
Bind the app to 127.0.0.1 (where possible) | Structurally removes the path that skips the Sidecar |
| Read-only root filesystem and entrypoint bypass | The Sidecar runs under the same security baseline as the app |
| Limited to Basic Auth | A minimal guard for admin UIs with few users. Not a replacement for SSO or RBAC |
The same pattern applies to other admin UIs without a login. For authentication to become a real boundary, though, also check whether the appâs bind address can be changed, whether the entry point terminates TLS, and whether a NetworkPolicy blocks the app port.