keycloak

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 17, 2026 License: GPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package keycloak provides Keycloak JWT token validation and claims extraction. It integrates with Keycloak's JWKS endpoint for RS256 token validation.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidToken is returned when the token is invalid.
	ErrInvalidToken = errors.New("invalid token")
	// ErrExpiredToken is returned when the token has expired.
	ErrExpiredToken = errors.New("token has expired")
	// ErrInvalidIssuer is returned when the token issuer doesn't match.
	ErrInvalidIssuer = errors.New("invalid token issuer")
	// ErrInvalidAudience is returned when the token audience doesn't match.
	ErrInvalidAudience = errors.New("invalid token audience")
	// ErrJWKSUnavailable is returned when JWKS cannot be fetched.
	ErrJWKSUnavailable = errors.New("JWKS endpoint unavailable")
	// ErrKeyNotFound is returned when the key ID is not found in JWKS.
	ErrKeyNotFound = errors.New("key not found in JWKS")
)

Functions

This section is empty.

Types

type Claims

type Claims struct {
	jwt.RegisteredClaims

	// Keycloak-specific claims
	PreferredUsername string      `json:"preferred_username"`
	Email             string      `json:"email"`
	EmailVerified     bool        `json:"email_verified"`
	Name              string      `json:"name"`
	GivenName         string      `json:"given_name"`
	FamilyName        string      `json:"family_name"`
	RealmAccess       RealmAccess `json:"realm_access"`

	// Resource access (client roles) - optional
	ResourceAccess map[string]RealmAccess `json:"resource_access,omitempty"`

	// Session info
	SessionState string `json:"session_state,omitempty"`
	Azp          string `json:"azp,omitempty"` // Authorized party (client ID)

	// Multi-tenant support
	TenantID    string   `json:"tenant_id,omitempty"`
	TenantRole  string   `json:"tenant_role,omitempty"`  // Primary role within tenant
	TenantRoles []string `json:"tenant_roles,omitempty"` // All roles within tenant
}

Claims represents Keycloak JWT token claims.

func (*Claims) GetClientRoles

func (c *Claims) GetClientRoles(clientID string) []string

GetClientRoles returns roles for a specific client.

func (*Claims) GetPrimaryRole

func (c *Claims) GetPrimaryRole() string

GetPrimaryRole returns the highest-priority role for backward compatibility. Priority: admin > user > viewer

func (*Claims) GetPrimaryTenantRole

func (c *Claims) GetPrimaryTenantRole() string

GetPrimaryTenantRole returns the highest-priority tenant role. Priority: admin > user > viewer

func (*Claims) GetRealmRoles

func (c *Claims) GetRealmRoles() []string

GetRealmRoles returns the realm-level roles.

func (*Claims) GetTenantID

func (c *Claims) GetTenantID() string

GetTenantID returns the tenant ID from the token.

func (*Claims) GetTenantRole

func (c *Claims) GetTenantRole() string

GetTenantRole returns the primary role within the tenant.

func (*Claims) GetTenantRoles

func (c *Claims) GetTenantRoles() []string

GetTenantRoles returns all roles within the tenant.

func (*Claims) GetUserID

func (c *Claims) GetUserID() string

GetUserID returns the subject (user ID) from the token.

func (*Claims) HasAnyRealmRole

func (c *Claims) HasAnyRealmRole(roles ...string) bool

HasAnyRealmRole checks if the user has any of the specified realm roles.

func (*Claims) HasAnyTenantRole

func (c *Claims) HasAnyTenantRole(roles ...string) bool

HasAnyTenantRole checks if the user has any of the specified tenant roles.

func (*Claims) HasClientRole

func (c *Claims) HasClientRole(clientID, role string) bool

HasClientRole checks if the user has a specific role for a client.

func (*Claims) HasRealmRole

func (c *Claims) HasRealmRole(role string) bool

HasRealmRole checks if the user has a specific realm role.

func (*Claims) HasTenantRole

func (c *Claims) HasTenantRole(role string) bool

HasTenantRole checks if the user has a specific role within the tenant.

type JWK

type JWK struct {
	Kid string `json:"kid"` // Key ID
	Kty string `json:"kty"` // Key Type (RSA)
	Alg string `json:"alg"` // Algorithm (RS256)
	Use string `json:"use"` // Key Use (sig)
	N   string `json:"n"`   // RSA modulus
	E   string `json:"e"`   // RSA exponent
}

JWK represents a JSON Web Key.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set.

type RealmAccess

type RealmAccess struct {
	Roles []string `json:"roles"`
}

RealmAccess represents the realm_access claim structure from Keycloak.

type RefreshErrorHandler

type RefreshErrorHandler func(err error, consecutiveFailures int)

RefreshErrorHandler is called when JWKS refresh fails. Use this to integrate with your alerting/monitoring system.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator validates Keycloak JWT tokens using JWKS.

func NewValidator

func NewValidator(ctx context.Context, cfg ValidatorConfig) (*Validator, error)

NewValidator creates a new Keycloak token validator.

func (*Validator) Close

func (v *Validator) Close() error

Close shuts down the JWKS background refresh.

func (*Validator) HasKeys

func (v *Validator) HasKeys() bool

HasKeys returns true if the validator has at least one key loaded.

func (*Validator) LastRefreshError

func (v *Validator) LastRefreshError() (error, int)

LastRefreshError returns the last refresh error and consecutive failure count. Returns nil, 0 if last refresh was successful.

func (*Validator) LastRefreshTime

func (v *Validator) LastRefreshTime() time.Time

LastRefreshTime returns the time of the last successful JWKS refresh.

func (*Validator) ValidateToken

func (v *Validator) ValidateToken(tokenString string) (*Claims, error)

ValidateToken validates a Keycloak JWT token and returns the claims.

type ValidatorConfig

type ValidatorConfig struct {
	JWKSURL         string
	IssuerURL       string
	Audience        string // Optional
	RefreshInterval time.Duration
	HTTPTimeout     time.Duration
	// OnRefreshError is called when background JWKS refresh fails.
	// Use for logging, alerting, or metrics.
	OnRefreshError RefreshErrorHandler
	// RequireInitialFetch if true, NewValidator will fail if initial JWKS fetch fails.
	// If false (default), the validator will start and retry in background.
	RequireInitialFetch bool
}

ValidatorConfig holds configuration for the token validator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL