Kube AuthKit is a lightweight Python library that unifies Kubernetes and Red Hat OpenShift authentication behind a single, consistent API. Whether you're running locally with kubeconfig, inside a pod with a service account, or authenticating via OIDC or OpenShift OAuth—it's one line of code.
If you've ever built Python applications that talk to Kubernetes or OpenShift clusters, you know the pain: different authentication methods require different code paths, token management is tedious, and what works on your laptop breaks inside a pod. We built Kube AuthKit to make that pain disappear.
In this post, I'll walk you through what Kube AuthKit does, how it works, and why it saves your team significant development time.
The problem: Authentication fragmentation
Kubernetes supports multiple authentication mechanisms—kubeconfig files, service account tokens, OIDC, and platform-specific methods like OpenShift OAuth. Each one has its own setup, its own token lifecycle, and its own quirks.
Consider a data science team building tools that need to run in 3 different contexts:
- Locally on a developer's laptop (using
~/.kube/config) - Inside a Jupyter Notebook running on OpenShift AI (using a mounted service account)
- In a continuous integration and continuous delivery (CI/CD) pipeline with OIDC credentials from an identity provider like Keycloak
Without a unified approach, you end up writing conditional logic for each environment, duplicating token-handling code, and debugging authentication failures that only appear in specific deployment contexts. Your code base becomes littered with if/elif blocks checking environment variables and file system paths.
The official Kubernetes Python client handles kubeconfig and in-cluster auth, but leaves OIDC and OpenShift OAuth to you.
The solution: One function, any environment
Kube AuthKit reduces all of this to a single function call:
from kube_authkit import get_k8s_client, AuthConfig
from kubernetes import client
# Works everywhere - laptop, pod, notebook, CI/CD
api_client = get_k8s_client(AuthConfig(method="auto"))
v1 = client.CoreV1Api(api_client)
pods = v1.list_pod_for_all_namespaces()
print(f"Found {len(pods.items)} pods")That's it. The library detects your environment automatically and selects the right authentication strategy. The returned ApiClient is a standard Kubernetes Python client object—fully compatible with any Kubernetes API you'd normally use.
How it works: The strategy pattern
Under the hood, Kube AuthKit uses the Strategy Pattern to encapsulate each authentication method behind a common interface.
AuthFactory (auto-detection)
├── OIDCStrategy (OpenID Connect)
├── OpenShiftOAuthStrategy (OpenShift OAuth)
├── InClusterStrategy (Service Account token)
└── KubeConfigStrategy (~/.kube/config)When you call get_k8s_client(AuthConfig(method="auto")) without explicit configuration, the AuthFactory probes the environment in a well-defined order:
- First, it checks for OIDC environment variables (
AUTHKIT_OIDC_ISSUER,AUTHKIT_CLIENT_ID)—if present, it initializes the OIDC strategy. - Next, it looks for a Bearer token—either passed programmatically via
AuthConfig.tokenor set via theAUTHKIT_TOKENorOPENSHIFT_TOKENenvironment variables. - After that, it detects in-cluster markers (
KUBERNETES_SERVICE_HOSTand the mounted service account). If running inside a pod, it adopts theInClusterStrategy. - Finally, it falls back to the
kubeconfigfile (KUBECONFIGenv variable or~/.kube/config). This serves as the default strategy for local development.
This ordering is deliberate: more specific, explicitly configured methods take precedence over implicit ones.
Which method fits your setup?
To help you decide which method fits your setup, use this reference:
| Where you're running | Auth method | Why |
|---|---|---|
| Inside a pod or notebook | In-cluster (service account) | Already mounted by the cluster, zero config needed |
| Developer laptop | kubeconfig | Uses your existing ~/.kube/config from oc login or kubectl |
| CI/CD pipeline with an IdP (such as Keycloak or Okta) | OIDC | Non-interactive flows for automation |
| OpenShift with a user token | OpenShift OAuth | Reuse your oc whoami -t token directly |
For vanilla Kubernetes without an external identity provider, the choice is straightforward: inside the cluster, use the service account; outside, use your kubeconfig. OIDC and OpenShift OAuth only come into play when you have an identity provider in the picture. Let’s look at how each of these strategies works in detail.
4 authentication strategies in detail
Kube AuthKit provides 4 distinct strategies to handle authentication across different deployment contexts.
1. kubeconfig: Local development
This is the most familiar method. Kube AuthKit reads your kubeconfig file (defaulting to ~/.kube/config) and delegates to the official Kubernetes Python client's load_kube_config(). It supports custom paths and context selection out of the box:
from kube_authkit import get_k8s_client, AuthConfig
config = AuthConfig(
method="kubeconfig",
kubeconfig_path="/path/to/custom/kubeconfig"
)
api_client = get_k8s_client(config)2. In-cluster: Pods and notebooks
When your code runs inside a Kubernetes pod (or an OpenShift AI notebook), the cluster automatically mounts a service account token at /var/run/secrets/kubernetes.io/serviceaccount/token. The InClusterStrategy detects this and configures the client accordingly, requiring zero configuration on your part.
3. OIDC: Enterprise identity providers
OIDC authentication is notoriously complex to implement correctly. The OIDCStrategy library supports two OAuth 2.0 flows.
The device code flow is ideal for CLI tools and headless environments:
config = AuthConfig(
method="oidc",
oidc_issuer="https://keycloak.example.com/auth/realms/myrealm",
client_id="my-cli-tool",
use_device_flow=True
)
api_client = get_k8s_client(config)
# Prints: "Visit https://... and enter code: ABCD-EFGH"Use the authorization code flow with PKCE for interactive, user-facing applications:
config = AuthConfig(
method="oidc",
oidc_issuer="https://keycloak.example.com/auth/realms/myrealm",
client_id="my-app",
use_device_flow=False
)
api_client = get_k8s_client(config)
# Opens browser for authenticationBoth flows handle OIDC discovery automatically (fetching the .well-known/openid-configuration endpoint), manage token refresh, and support custom CA certificates for private PKI.
4. OpenShift OAuth (platform-native auth)
For OpenShift environments, the library discovers the built-in OAuth server via the .well-known/oauth-authorization-server endpoint. It supports both explicit token injection and interactive browser-based login:
# Using an explicit token (e.g., from `oc whoami -t`)
config = AuthConfig(
method="openshift",
token="sha256~abc123...",
k8s_api_host="https://api.cluster.example.com:6443"
)
api_client = get_k8s_client(config)Token lifecycle management: Set it and forget it
One of the most error-prone aspects of OIDC-based authentication is token lifecycle management. Kube AuthKit handles this transparently under the hood with 2 built-in storage strategies:
- In-memory storage (default): Tokens live only for the duration of your process. This is the most secure option for automated CI/CD pipelines and headless environments, as credentials are never written to disk.
- System keyring storage (opt-in): To avoid constantly re-authenticating during local development, active session credentials and refresh tokens are persisted securely in your OS keyring (macOS Keychain, GNOME Keyring, or Windows Credential Vault). The first run requires interactive authentication; subsequent runs reuse the stored refresh token to silently request new short-lived access tokens behind the scenes.
config = AuthConfig(
method="oidc",
oidc_issuer="https://keycloak.example.com/auth/realms/myrealm",
client_id="my-app",
use_keyring=True # Persist tokens in system keyring
)
# First run: browser opens for authentication
# Next run: uses stored refresh token - no interaction needed
api_client = get_k8s_client(config)3 entry points for different needs
The library provides 3 public functions to cover different use cases:
| Function | Returns | Use case |
|---|---|---|
get_k8s_client(config) | kubernetes.client.ApiClient | Most common—ready-to-use Kubernetes client |
get_k8s_config(config) | kubernetes.client.Configuration | When you need to customize the config before creating a client |
get_token(config) | str | When you just need the raw bearer token (for example, for custom HTTP calls) |
The get_k8s_config() function is particularly useful when you need fine-grained control:
from kube_authkit import get_k8s_config
from kubernetes import client
k8s_config = get_k8s_config()
k8s_config.debug = True # Enable debug logging
api_client = client.ApiClient(k8s_config)Twelve-factor configuration: Code, environment, or both
Kube AuthKit supports configuration through AuthConfig objects, environment variables, or a combination of both. Environment variables are loaded automatically by default, allowing environment-specific settings to override code defaults. However, if you need strict programmatic control, explicit values passed directly into the AuthConfig constructor will take ultimate precedence.
This means you can write code that uses AuthConfig defaults in development and override them with environment variables in production—without changing a single line:
#from kube_authkit import get_k8s_client, AuthConfig
# In your code - always the same
api_client = get_k8s_client(AuthConfig(method="auto"))
# In development: uses ~/.kube/config (auto-detected)
# In production: set AUTHKIT_OIDC_ISSUER and AUTHKIT_CLIENT_ID
# In a pod: uses in-cluster service account (auto-detected)You can also load configuration from dictionaries, making it easy to integrate with YAML or JSON config files:
import yaml
from kube_authkit import AuthConfig, get_k8s_client
with open("auth-config.yaml") as f:
config = AuthConfig.from_dict(yaml.safe_load(f))
api_client = get_k8s_client(config)Security defaults
Kube AuthKit was designed with security as a first-class concern:
- Strict TLS verification: Secure transport is enabled by default. You must explicitly opt out by passing an insecure flag, only disable this in local development.
- Zero log leakage: No sensitive data is ever logged. To prevent credential leaks in production monitoring tools, token values are automatically redacted in
AuthConfig.__repr__()and never appear in log output. - Minimal dependencies: The core library depends on
kubernetes,requests,PyJWT, andurllib3. Fewer dependencies mean a smaller attack surface and simpler software supply chain management. - OS-native credential isolation: Tokens stored via the keyring are protected directly by your operating system's credential manager, ensuring active session credentials are never written to disk in plain text files.
Empowering teams: Who benefits from Kube AuthKit?
Kube AuthKit simplifies Kubernetes authentication for various development and platform roles across different environments.
Data science and ML teams
Teams using Red Hat OpenShift AI or Kubeflow often write Python code that needs to interact with the Kubernetes API—submitting training jobs, managing pipelines, or querying cluster state. These tools need to work both locally (during development) and inside notebooks or pods (in production). Kube AuthKit eliminates the "works on my machine" problem by reliably bridging local IDEs and cluster runtimes.
Platform engineering teams
If you're building internal developer platforms (IDPs) or CLIs that target Kubernetes or OpenShift, you need to support multiple authentication methods for different user populations without injecting credential-handling overhead. Kube AuthKit gives you that out of the box, providing a clean, unified interface that your users can configure via environment variables.
Application developers
Any Python application that talks to the Kubernetes API benefits from not having to implement complex authentication logic from scratch—especially OIDC, which traditionally requires wrangling discovery endpoints, PKCE, token refresh, and secure storage.
Multi-environment authentication
- Simplified multi-environment authentication: One function call replaces dozens of lines of conditional auth logic.
- Production-grade OIDC: Supports 2 OAuth 2.0 flows (device code and authorization code with PKCE) out of the box, fully tested and complete with automated token refresh.
- Extensible, strategy-based design: Built on the strategy pattern, making it straightforward to add new custom authentication methods without modifying the core code base.
- Hardened security defaults: Enforces TLS verification by default, redacts sensitive data, and operates with minimal dependencies.
- Native client compatibility: Returns a standard, fully configured
ApiClient, ensuring compatibility with the official Kubernetes Python library without introducing vendor lock-in. - Zero-redeploy configurations: Deploy the same code across environments by changing environment variables, not code.
Trade-offs
- Python-centric: Currently exclusive to the Python ecosystem. Teams using Go, Java, or other languages will need alternatives. (Though the architectural patterns translate well.)
- OIDC flows require user interaction for initial authentication: Device code and authorization code flows inherently need a human to authenticate at least once. The keyring feature mitigates repeat logins.
- Limited to Kubernetes API authentication. This library authenticates you to the Kubernetes API server (AuthN)—it doesn't handle application-level authentication or cluster-level RBAC policies (AuthZ) that must still be managed separately inside the cluster.
- Opt-in storage dependencies: To maintain a lightweight core footprint, persistent OS Keyring storage is packaged as an optional extra (
pip install kube-authkit[keyring]).
Getting started
Install the library:
pip install kube-authkit
# Or with keyring support:
pip install kube-authkit[keyring]Try the simplest possible usage:
from kube_authkit import get_k8s_client, AuthConfig
from kubernetes import client
api_client = get_k8s_client(AuthConfig(method="auto"))
v1 = client.CoreV1Api(api_client)
for ns in v1.list_namespace().items:
print(ns.metadata.name)Explore the examples directory for more detailed scenarios including device flow authentication, notebook integration, and custom CA certificates.
Get started with Kube AuthKit
Kube AuthKit is actively maintained by the Open Data Hub community, the upstream open source project that serves as the foundation for Red Hat OpenShift AI. The library is currently at version 0.4.0 and is being used in production across OpenShift AI environments. Contributions are welcome—whether it's new authentication strategies, improved documentation, or bug fixes.
Explore the code base, star the repository, or open a pull request on GitHub.
Note
Kube AuthKit is an open source project under the Apache License 2.0. It wraps and extends the official Kubernetes Python Client to provide simplified authentication workflows for OpenShift AI and Kubernetes environments.