Skip to content

Repository files navigation

go-k8s-auth

Echo middleware that authenticates HTTP requests using the Kubernetes TokenReview API.

Install

go get github.com/DKE-Data/go-k8s-auth

Quick Start

package main

import (
    "net/http"

    "github.com/labstack/echo/v4"
    k8sauth "github.com/DKE-Data/go-k8s-auth"
)

func main() {
    e := echo.New()

    e.Use(k8sauth.TokenReview(k8sauth.TokenReviewConfig{}))

    e.GET("/whoami", func(c echo.Context) error {
        user := k8sauth.GetUserInfo(c)
        return c.JSON(http.StatusOK, user)
    })

    e.Logger.Fatal(e.Start(":8080"))
}

With zero configuration the middleware creates a Kubernetes client from in-cluster config (falling back to ~/.kube/config) and validates the Bearer token from each request's Authorization header. On success it stores a *k8sauth.UserInfo in the Echo context.

Configuration

All fields are optional:

k8sauth.TokenReview(k8sauth.TokenReviewConfig{
    // Skip authentication for certain requests.
    Skipper: func(c echo.Context) bool {
        return c.Path() == "/healthz"
    },

    // Require the token to be valid for specific audiences.
    Audiences: []string{"https://my-api.example.com"},

    // Provide your own Kubernetes clientset.
    // If nil, one is created automatically (in-cluster, then kubeconfig).
    // Panics at init if neither is available.
    Client: myClientset,

    // Key used to store UserInfo in the Echo context. Default: "user".
    ContextKey: "k8s-user",
})

Retrieving User Info

Use the helper to get the authenticated identity in your handlers:

user := k8sauth.GetUserInfo(c)
// user.Username  - e.g. "system:serviceaccount:default:my-sa"
// user.UID
// user.Groups    - e.g. ["system:serviceaccounts", "system:serviceaccounts:default"]
// user.Extra     - e.g. {"authentication.kubernetes.io/pod-name": ["my-pod"]}

GetUserInfo returns nil if the request was not authenticated (e.g. the route was skipped).

Note: GetUserInfo always reads from the "user" context key. If you set a custom ContextKey, retrieve the value directly with c.Get("k8s-user") and type-assert to *k8sauth.UserInfo.

Error Responses

Condition Status Message
No Authorization header 401 missing authorization header
Not Bearer <token> format 401 invalid authorization header format
Token rejected by Kubernetes 401 token authentication failed
TokenReview API unreachable 500 authentication service unavailable

All errors are returned as echo.HTTPError with a JSON body {"message": "..."}.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages