Echo middleware that authenticates HTTP requests using the Kubernetes TokenReview API.
go get github.com/DKE-Data/go-k8s-auth
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.
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",
})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:
GetUserInfoalways reads from the"user"context key. If you set a customContextKey, retrieve the value directly withc.Get("k8s-user")and type-assert to*k8sauth.UserInfo.
| 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": "..."}.