keycloak

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 9 Imported by: 0

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.

fork of https://github.com/stillya/testcontainers-keycloak

Installation

go get github.com/burner-account/testcontainers-keycloak

Usage

package main

import (
	"context"
	"fmt"
	keycloak "github.com/burner-account/testcontainers-keycloak"
	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/wait"
	"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.RunContainer(ctx,
		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 WithDBPassword

func WithDBPassword(value string) testcontainers.CustomizeRequestOption

WithDBPassword sets the password of the database user.

func WithDBUrl

WithDBUrl sets the full database JDBC URL.

func WithDBUsername

func WithDBUsername(value string) testcontainers.CustomizeRequestOption

WithDBUsername sets the username of the database user.

func WithHTTPRelativePath

func WithHTTPRelativePath(value string) testcontainers.CustomizeRequestOption

WithHTTPRelativePath sets the path relative to / for serving resources. The path must start with a /.

func WithHTTPSCertFile

func WithHTTPSCertFile(value string) testcontainers.CustomizeRequestOption

WithHTTPSCertFile sets the file path to a server certificate or certificate chain in PEM format.

func WithHTTPSCertKeyFile

func WithHTTPSCertKeyFile(value string) testcontainers.CustomizeRequestOption

WithHTTPSCertKeyFile sets the file path to a private key in PEM format.

func WithHealth

func WithHealth(enabled string) testcontainers.CustomizeRequestOption

WithHealth is option to enable the health check endpoint.

func WithHostname

func WithHostname(value string) testcontainers.CustomizeRequestOption

WithHostname sets the hostname for the Keycloak server.

func WithHostnameAdmin

func WithHostnameAdmin(value string) testcontainers.CustomizeRequestOption

WithHostnameAdmin sets the hostname for accessing the administration console.

func WithHostnamePath

func WithHostnamePath(value string) testcontainers.CustomizeRequestOption

WithHostnamePath should be used if proxy uses a different context-path for Keycloak.

func WithLogLevel

func WithLogLevel(value string) testcontainers.CustomizeRequestOption

WithLogLevel sets the log level of the root category or a comma-separated list of individual categories and their levels.

func WithMetrics

func WithMetrics(enabled string) testcontainers.CustomizeRequestOption

WithMetrics is option to enable metrics.

func WithProviders

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 WithProxy deprecated

WithProxy sets the proxy address forwarding mode if the server is behind a reverse proxy.

Deprecated: Use proxy-headers instead.

func WithProxyHeaders

func WithProxyHeaders(value string) testcontainers.CustomizeRequestOption

WithProxyHeaders sets the proxy headers that should be accepted by the server.

func WithRealmImportFile

func WithRealmImportFile(realmImportFile string) testcontainers.CustomizeRequestOption

WithRealmImportFile is option to import a realm file into KeycloakContainer.

func WithTLS

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 RunContainer

RunContainer 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