keycloak

package module
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 9 Imported by: 1

README

Keycloak Testcontainer - testcontainers implementation for Keycloak SSO.

Build Status Coverage Go Reference

  • Native integration with Testcontainers.
  • Customization via realm.json to create custom realms, users, clients, etc.
  • Provides AdminClient to interact with Keycloak API.
  • Customization via jar's providers.
  • TLS support.

Installation

go get github.com/stillya/testcontainers-keycloak

Usage

package main

import (
	"context"
	"fmt"
	keycloak "github.com/stillya/testcontainers-keycloak"
	"os"
	"testing"
)

var keycloakContainer *keycloak.KeycloakContainer

func Test_Example(t *testing.T) {
	ctx := context.Background()

	authServerURL, err := keycloakContainer.GetAuthServerURL(ctx)
	if err != nil {
		t.Errorf("GetAuthServerURL() error = %v", err)
		return
	}

	fmt.Println(authServerURL)
	// Output:
	// http://localhost:32768/auth
}

func TestMain(m *testing.M) {
	defer func() {
		if r := recover(); r != nil {
			shutDown()
			fmt.Println("Panic")
		}
	}()
	setup()
	code := m.Run()
	shutDown()
	os.Exit(code)
}

func setup() {
	var err error
	ctx := context.Background()
	keycloakContainer, err = RunContainer(ctx)
	if err != nil {
		panic(err)
	}
}

func shutDown() {
	ctx := context.Background()
	err := keycloakContainer.Terminate(ctx)
	if err != nil {
		panic(err)
	}
}

func RunContainer(ctx context.Context) (*keycloak.KeycloakContainer, error) {
	return keycloak.Run(ctx,
		"keycloak/keycloak:24.0",
		keycloak.WithContextPath("/auth"),
		keycloak.WithRealmImportFile("../testdata/realm-export.json"),
		keycloak.WithAdminUsername("admin"),
		keycloak.WithAdminPassword("admin"),
	)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClientContext

func ClientContext(ctx context.Context, client *http.Client) context.Context

ClientContext returns a new context with the given HTTP client Used to pass a custom HTTP client to the AdminClient

func WithAdminPassword

func WithAdminPassword(password string) testcontainers.CustomizeRequestOption

WithAdminPassword is option to set the admin password for KeycloakContainer.

func WithAdminUsername

func WithAdminUsername(username string) testcontainers.CustomizeRequestOption

WithAdminUsername is option to set the admin username for KeycloakContainer.

func WithContextPath

func WithContextPath(contextPath string) testcontainers.CustomizeRequestOption

WithContextPath is option to set the context path for KeycloakContainer.

func WithProviders added in v0.1.1

func WithProviders(providerFiles ...string) testcontainers.CustomizeRequestOption

WithProviders is option to set the providers for KeycloakContainer. Providers should be packaged ina Java Archive (JAR) file. See https://www.keycloak.org/server/configuration-provider

func WithRealmImportFile

func WithRealmImportFile(realmImportFile string) testcontainers.CustomizeRequestOption

WithRealmImportFile is option to import a realm file into KeycloakContainer.

func WithTLS added in v0.1.1

func WithTLS(certFile, keyFile string) testcontainers.CustomizeRequestOption

WithTLS is option to enable TLS for KeycloakContainer.

Types

type AdminClient

type AdminClient struct {
	ServerURL string
	Realm     string
	Username  string
	Password  string
	ClientID  string
	UseTLS    bool
	// contains filtered or unexported fields
}

AdminClient is a Keycloak admin client.

func NewAdminClient

func NewAdminClient(ctx *context.Context, serverURL, username, password string) (*AdminClient, error)

NewAdminClient creates a new Keycloak admin client.

func (*AdminClient) GetClient

func (a *AdminClient) GetClient(realm string, clientID string) (*Client, error)

GetClient returns a Keycloak client.

type Client

type Client struct {
	Access                             *map[string]interface{} `json:"access,omitempty"`
	AdminURL                           *string                 `json:"adminUrl,omitempty"`
	Attributes                         *map[string]string      `json:"attributes,omitempty"`
	AuthenticationFlowBindingOverrides *map[string]string      `json:"authenticationFlowBindingOverrides,omitempty"`
	AuthorizationServicesEnabled       *bool                   `json:"authorizationServicesEnabled,omitempty"`
	BaseURL                            *string                 `json:"baseUrl,omitempty"`
	BearerOnly                         *bool                   `json:"bearerOnly,omitempty"`
	ClientAuthenticatorType            *string                 `json:"clientAuthenticatorType,omitempty"`
	ClientID                           *string                 `json:"clientId,omitempty"`
	ConsentRequired                    *bool                   `json:"consentRequired,omitempty"`
	DefaultClientScopes                *[]string               `json:"defaultClientScopes,omitempty"`
	DefaultRoles                       *[]string               `json:"defaultRoles,omitempty"`
	Description                        *string                 `json:"description,omitempty"`
	DirectAccessGrantsEnabled          *bool                   `json:"directAccessGrantsEnabled,omitempty"`
	Enabled                            *bool                   `json:"enabled,omitempty"`
	FrontChannelLogout                 *bool                   `json:"frontchannelLogout,omitempty"`
	FullScopeAllowed                   *bool                   `json:"fullScopeAllowed,omitempty"`
	ID                                 *string                 `json:"id,omitempty"`
	ImplicitFlowEnabled                *bool                   `json:"implicitFlowEnabled,omitempty"`
	Name                               *string                 `json:"name,omitempty"`
	NodeReRegistrationTimeout          *int32                  `json:"nodeReRegistrationTimeout,omitempty"`
	NotBefore                          *int32                  `json:"notBefore,omitempty"`
	OptionalClientScopes               *[]string               `json:"optionalClientScopes,omitempty"`
	Origin                             *string                 `json:"origin,omitempty"`
	Protocol                           *string                 `json:"protocol,omitempty"`
	PublicClient                       *bool                   `json:"publicClient,omitempty"`
	RedirectURIs                       *[]string               `json:"redirectUris,omitempty"`
	RegisteredNodes                    *map[string]int         `json:"registeredNodes,omitempty"`
	RegistrationAccessToken            *string                 `json:"registrationAccessToken,omitempty"`
	RootURL                            *string                 `json:"rootUrl,omitempty"`
	Secret                             *string                 `json:"secret,omitempty"`
	ServiceAccountsEnabled             *bool                   `json:"serviceAccountsEnabled,omitempty"`
	StandardFlowEnabled                *bool                   `json:"standardFlowEnabled,omitempty"`
	SurrogateAuthRequired              *bool                   `json:"surrogateAuthRequired,omitempty"`
	WebOrigins                         *[]string               `json:"webOrigins,omitempty"`
}

Client represents a Keycloak client(https://www.keycloak.org/docs-api/19.0.3/javadocs/org/keycloak/representations/idm/ClientRepresentation.html).

type KeycloakContainer

type KeycloakContainer struct {
	testcontainers.Container
	// contains filtered or unexported fields
}

KeycloakContainer is a wrapper around testcontainers.Container that provides some convenience methods for working with Keycloak.

func Run added in v0.3.0

Run starts a new KeycloakContainer with the given options.

func (*KeycloakContainer) GetAdminClient

func (k *KeycloakContainer) GetAdminClient(ctx context.Context) (*AdminClient, error)

GetAdminClient returns an AdminClient for the KeycloakContainer.

func (*KeycloakContainer) GetAuthServerURL

func (k *KeycloakContainer) GetAuthServerURL(ctx context.Context) (string, error)

GetAuthServerURL returns the URL of the KeycloakContainer.

type Token

type Token struct {
	AccessToken      string `json:"access_token"`
	IDToken          string `json:"id_token"`
	ExpiresIn        int    `json:"expires_in"`
	RefreshExpiresIn int    `json:"refresh_expires_in"`
	RefreshToken     string `json:"refresh_token"`
	TokenType        string `json:"token_type"`
	NotBeforePolicy  int    `json:"not-before-policy"`
	SessionState     string `json:"session_state"`
	Scope            string `json:"scope"`
}

Token represents a Keycloak token.

Jump to

Keyboard shortcuts

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