Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Kube AuthKit: Unified Kubernetes and OpenShift auth in Python

October 2, 2026
Saad Zaher
Related topics:
PythonKubernetesDeveloper tools
Related products:
Red Hat OpenShift AIRed Hat OpenShift

    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:

    1. First, it checks for OIDC environment variables (AUTHKIT_OIDC_ISSUER, AUTHKIT_CLIENT_ID)—if present, it initializes the OIDC strategy.
    2. Next, it looks for a Bearer token—either passed programmatically via AuthConfig.token or set via the AUTHKIT_TOKEN or OPENSHIFT_TOKEN environment variables.
    3. After that, it detects in-cluster markers (KUBERNETES_SERVICE_HOST and the mounted service account). If running inside a pod, it adopts the InClusterStrategy.
    4. Finally, it falls back to the kubeconfig file (KUBECONFIG env 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 runningAuth methodWhy
    Inside a pod or notebookIn-cluster (service account)Already mounted by the cluster, zero config needed
    Developer laptopkubeconfigUses your existing ~/.kube/config from oc login or kubectl
    CI/CD pipeline with an IdP (such as Keycloak or Okta)OIDCNon-interactive flows for automation
    OpenShift with a user tokenOpenShift OAuthReuse 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 authentication

    Both 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:

    FunctionReturnsUse case
    get_k8s_client(config)kubernetes.client.ApiClientMost common—ready-to-use Kubernetes client
    get_k8s_config(config)kubernetes.client.ConfigurationWhen you need to customize the config before creating a client
    get_token(config)strWhen 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, and urllib3. 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.

    Related Posts

    • Guide to configuring multiple authentication providers in Developer Hub

    • Advanced authentication and authorization for MCP Gateway

    • Multicluster authentication with Ansible Automation Platform

    • Backstage authentication and catalog providers: A practical guide

    • Fine-grained authorization for Quarkus microservices

    Recent Posts

    • Benchmarking AI decision models against traditional guardrails

    • Kube AuthKit: Unified Kubernetes and OpenShift auth in Python

    • Smarter GPU sharing: How Red Hat build of Kueue works with dynamic resource allocation

    • Master your skills: Building skills you can trust

    • GPU virtualization at scale: AMD MI300X SR-IOV on Red Hat OpenStack Services on OpenShift

    What’s up next?

    Learning Path RHEL platform card

    Build a Python Flask application with Red Hat Hardened Images

    Develop a Flask application using Red Hat hardened images and Red Hat build...
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility
    Ask AI