keycloak

package module
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

README

Testcontainers for Go modules

keycloak

import (
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/bigkevmcd/testcontainer-modules/keycloak"
)

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

	keycloakContainer, err := keycloak.Run(ctx,
		"quay.io/keycloak/keycloak:26.0.6-0",
		keycloak.WithAdminCredentials("administrator", "secretpassword"),
	)
	require.NoError(t, err)
	testcontainers.CleanupContainer(t, keycloakContainer)

	token, err := keycloakContainer.GetBearerToken(ctx, "master", "administrator", "secretpassword")
	require.NoError(t, err)
	require.NotEmpty(t, token)

	err := keycloakContainer.CreateUser(ctx, "master", token,
		keycloak.UserRepresentation{Username: "testing-user", Enabled: true})
	require.NoError(t, err)

	// This allows the use of arbitrary attributes on created users.
	require.NoError(t, keycloakContainer.EnableUnmanagedAttributes(ctx, token))
}

This makes it easy to start a Keycloak server as a test container.

The container is started in "development mode".

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadKeycloakError added in v0.0.9

func ReadKeycloakError(resp *http.Response) error

ReadKeycloakError parses an HTTP Response and returns an error with the message from Keycloak.

func WithAdminCredentials

func WithAdminCredentials(username, password string) testcontainers.CustomizeRequestOption

WithAdminCredentials sets the admin username and password.

func WithImportRealm

func WithImportRealm(realmFile string) testcontainers.CustomizeRequestOption

WithImportRealm sets the container up to read from a Realm export.

Types

type ClientRepresentation added in v0.0.9

type ClientRepresentation struct {
	ID                        string            `json:"id,omitempty"`
	ClientID                  string            `json:"clientId"`
	Name                      string            `json:"name,omitempty"`
	Description               string            `json:"description,omitempty"`
	Type                      string            `json:"type,omitempty"`
	Enabled                   bool              `json:"enabled"`
	Secret                    string            `json:"secret,omitempty"`
	PublicClient              bool              `json:"publicClient"`
	ServiceAccountsEnabled    bool              `json:"serviceAccountsEnabled"`
	DirectAccessGrantsEnabled bool              `json:"directAccessGrantsEnabled"`
	DefaultRoles              []string          `json:"defaultRoles,omitempty"`
	Access                    map[string]any    `json:"access,omitempty"`
	Attributes                map[string]string `json:"attributes,omitempty"`
	Protocol                  string            `json:"protocol,omitempty"`
}

ClientRepresentation describes a Keycloak client.

type CredentialRepresentation added in v0.0.4

type CredentialRepresentation struct {
	Algorithm         string `json:"algorithm,omitempty"`
	Counter           int32  `json:"counter,omitempty"`
	Device            string `json:"device,omitempty"`
	Digits            int32  `json:"digits,omitempty"`
	HashedSaltedValue string `json:"hashedSaltedValue,omitempty"`
	HashIterations    int32  `json:"hashIterations,omitempty"`
	Period            int32  `json:"period,omitempty"`
	Salt              string `json:"salt,omitempty"`
	Temporary         *bool  `json:"temporary,omitempty"`
	Type              string `json:"type,omitempty"`
	Value             string `json:"value,omitempty"`
}

CredentialRepresentation represents credentials for a user or client TODO: Custom unmarshal timestamps from Keycloak!

Converted from https://www.keycloak.org/docs-api/latest/rest-api/index.html#CredentialRepresentation

type KeycloakContainer

type KeycloakContainer struct {
	testcontainers.Container
}

KeycloakContainer executes Keycloak and provides additional functionality for interacting with a running Keycloak server.

func Run

Run creates an instance of the Keycloak container type.

Example
ctx := context.Background()

keycloakContainer, err := keycloak.Run(ctx,
	testImage,
)
defer func() {
	if err := testcontainers.TerminateContainer(keycloakContainer); err != nil {
		log.Printf("failed to terminate container: %s", err)
	}
}()
if err != nil {
	log.Printf("failed to start container: %s", err)
	return
}
// }

state, err := keycloakContainer.State(ctx)
if err != nil {
	log.Printf("failed to get container state: %s", err)
	return
}

fmt.Println(state.Running)
Output:

true

func (*KeycloakContainer) AddClientRoleToServiceAccount added in v0.0.9

func (k *KeycloakContainer) AddClientRoleToServiceAccount(ctx context.Context, realmName, token, clientID, roleName string) error

AddClientRoleToServiceAccount adds a client role to the service account user of a client. This is useful for granting permissions to service accounts for machine-to-machine communication.

The roleName should be the name of an existing role in the target client. The clientID is the UUID of the client that owns the role.

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_post_adminrealmsrealmusersuser_idrole_mappingsclientsClient_uuid

func (*KeycloakContainer) CreateClient added in v0.0.9

func (k *KeycloakContainer) CreateClient(ctx context.Context, realmName, token string, cr ClientRepresentation) error

CreateClient creates an OIDC client.

realmName is the name of the realm e.g. "master"

Use GetClientUUID to get the ID of the newly created client.

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_post_adminrealmsrealmclients

func (*KeycloakContainer) CreateRealm added in v0.0.9

func (k *KeycloakContainer) CreateRealm(ctx context.Context, token string, rr RealmRepresentation) (string, error)

CreateRealm creates a realm with the provided representation.

Returns the UUID of the created realm.

func (*KeycloakContainer) CreateUser

func (k *KeycloakContainer) CreateUser(ctx context.Context, realmName, token string, ur UserRepresentation) (string, error)

CreateUser creates an user with the provided details.

realmName is the name of the realm e.g. "master"

Returns the UUID of the created user.

func (*KeycloakContainer) EnableUnmanagedAttributes added in v0.0.3

func (k *KeycloakContainer) EnableUnmanagedAttributes(ctx context.Context, realmName, token string) error

EnableUnmanagedAttributes modifies the realm to allow unmanaged attributes.

realmName is the name of the realm e.g. "master"

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_get_adminrealmsrealmusersprofile

func (*KeycloakContainer) EndpointPath

func (k *KeycloakContainer) EndpointPath(ctx context.Context, path string, opts ...func(*url.URL)) (string, error)

EndpointPath returns a URL that is relative to the container endpoint.

The path must be fully qualified e.g. /admin/realms/master/users

func (*KeycloakContainer) GenerateClientSecret added in v0.0.9

func (k *KeycloakContainer) GenerateClientSecret(ctx context.Context, realmName, token, clientID string) (secret string, clientErr error)

GenerateClientSecret regenerates the client token for a client.

realmName is the name of the realm e.g. "master" clientID is the UUID of the client e.g. "6f18e746-df4a-4e8f-85db-3424e6c73b10"

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_post_adminrealmsrealmclientsclient_uuidclient_secret

func (*KeycloakContainer) GetBearerToken

func (k *KeycloakContainer) GetBearerToken(ctx context.Context, realmName, username, password string) (string, error)

GetBearerToken makes a call to the OpenID endpoint to request a token.

The request is authenticated with the provided username/password.

realmName is the name of the realm e.g. "master"

This uses the admin-cli client ID.

func (*KeycloakContainer) GetClient added in v0.0.9

func (k *KeycloakContainer) GetClient(ctx context.Context, realmName, token, clientID string) (repr *ClientRepresentation, clientErr error)

GetClient gets the representation for a named client in a realm.

realmName is the name of the realm e.g. "master" clientID is the ID of the client e.g. "test-client"

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_get_adminrealmsrealmclients

func (*KeycloakContainer) GetClientSecret added in v0.0.9

func (k *KeycloakContainer) GetClientSecret(ctx context.Context, realmName, token, clientID string) (secret string, clientErr error)

GetClientSecret gets the token for accessing the API as a specific client.

realmName is the name of the realm e.g. "master" clientID is the UUID of the client e.g. "6f18e746-df4a-4e8f-85db-3424e6c73b10"

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_get_adminrealmsrealmclientsclient_uuidclient_secret

func (*KeycloakContainer) GetServiceAccountUser added in v0.0.9

func (k *KeycloakContainer) GetServiceAccountUser(ctx context.Context, realmName, token, clientID string) (*UserRepresentation, error)

GetServiceAccountUser gets the service account user for a client.

realmName is the name of the realm e.g. "master" clientID is the UUID of the client e.g. "6f18e746-df4a-4e8f-85db-3424e6c73b10"

This user is automatically created when a client has serviceAccountsEnabled set to true.

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_get_adminrealmsrealmclientsclient_uuidservice_account_user

func (*KeycloakContainer) SetUserPassword added in v0.0.4

func (k *KeycloakContainer) SetUserPassword(ctx context.Context, realmName, token, userID, password string) error

SetUserPassword sets a user password.

realmName is the name of the realm e.g. "master" userID is the ID of the user within ther realm e.g. "3af96c8e-4105-44eb-bf8c-2b44ff9194bb"

https://www.keycloak.org/docs-api/latest/rest-api/index.html#_put_adminrealmsrealmusersuser_idreset_password

type KeycloakError added in v0.0.9

type KeycloakError struct {
	Response   map[string]any
	StatusCode int
}

KeycloakError parses a Keycloak error response.

func (KeycloakError) Error added in v0.0.9

func (e KeycloakError) Error() string

type RealmRepresentation added in v0.0.9

type RealmRepresentation struct {
	Realm   string `json:"realm"`
	Enabled bool   `json:"enabled"`
}

RealmRepresentation is used to create new Realms.

type RoleRepresentation added in v0.0.9

type RoleRepresentation struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Composite   bool   `json:"composite,omitempty"`
	ClientRole  bool   `json:"clientRole,omitempty"`
	ContainerID string `json:"containerId,omitempty"`
}

RoleRepresentation represents a role in Keycloak Converted from https://www.keycloak.org/docs-api/latest/rest-api/index.html#RoleRepresentation

type UserRepresentation added in v0.0.9

type UserRepresentation struct {
	ID            string `json:"id,omitempty"`
	Username      string `json:"username"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"emailVerified"`
	Enabled       bool   `json:"enabled"`
	Firstname     string `json:"firstName,omitempty"`
	Lastname      string `json:"lastName,omitempty"`

	Attributes map[string][]string `json:"attributes,omitempty"`
}

UserRepresentation represents a user in Keycloak Simplified version for service account purposes.

Jump to

Keyboard shortcuts

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