Skip to main content

API Key Auth

API Key authentication via a header or query parameter. Default header: X-API-Key.

Usage

import "github.com/Pavan-Silva/go-zen/auth"

apiKeyAuth := &auth.APIKeyAuth{
Validate: func(apiKey string) (*auth.User, error) {
if apiKey == "sk-abc123" {
return &auth.User{
ID: "svc-1",
Username: "my-service",
Authorities: auth.Authorities("ROLE_SERVICE"),
}, nil
}
return nil, fmt.Errorf("invalid API key")
},
}

r.Use(auth.RequireAuth(apiKeyAuth))

Custom Header

apiKeyAuth := &auth.APIKeyAuth{
HeaderName: "X-Custom-Key",
Validate: validator,
}

How It Works

  • Reads from the configured header (default X-API-Key)
  • Passes the value to the validator function
  • Returns 401 Unauthorized on failure or missing header
  • Stores the returned User in the context on success