Skip to content

API Key Auth ​

Added: v1.1.0

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

Usage ​

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

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

r.EnableAuth(apiKeyAuth)

Custom Header ​

go
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

Released under the MIT License.